-
Notifications
You must be signed in to change notification settings - Fork 4k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
firebase_auth: App does not automatically login on startup in release build #17047
Comments
Hi @centy, I'm unable to reproduce this issue with the firebase_auth example app. Kindly provide a complete minimal example reproducing this issue. Also, you could reference the example app to ensure you're not missing anything in your implementation. |
Is there any way to turn on any verbose logging? |
Hi @centy, I'm not entirely sure on what you're trying to achieve with the verbose logging. Were you able to test with the firebase_auth example app I linked? |
I found guilty code: `
` |
I'll close this now, as it isn't a bug in FlutterFire. |
@SelaseKay why are you closing it? I have to initialize Firebase in izolate and login not working then |
You don't need to initialize firebase in an isolate. You can do that in your main function. Kindly reference the firebase_auth example app. |
@SelaseKay Unfortunately I have to because other features of Firebase are not working in isolate E/flutter ( 9709): [ERROR:flutter/runtime/dart_vm_initializer.cc(40)] Unhandled Exception: [core/no-app] No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp() |
Could you provide a complete example reproducing this issue? |
|
I'm still unable to reproduce this issue. I followed these steps
Additionally, I made a few slight modifications to the sample you shared. Please have a look and see if it helps. import 'dart:async';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_auth_example/firebase_options.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:flutter/material.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
FirebaseAuth.instance.authStateChanges().listen((user) async {
print('Auth state changed: ${user?.uid}');
});
unawaited(
compute(
(args) async {
final token = args['token']! as RootIsolateToken;
BackgroundIsolateBinaryMessenger.ensureInitialized(token);
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
await Future.delayed(const Duration(seconds: 200));
},
{
'token': RootIsolateToken.instance,
},
),
);
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final FirebaseAuth _auth = FirebaseAuth.instance;
final GoogleSignIn _googleSignIn = GoogleSignIn();
bool _isLoading = false;
Future<void> _signInWithGoogle() async {
try {
setState(() {
_isLoading = true;
});
// Start the Google Sign-In process
final GoogleSignInAccount? googleUser = await _googleSignIn.signIn();
if (googleUser == null) return;
// Obtain auth details from request
final GoogleSignInAuthentication googleAuth = await googleUser.authentication;
// Create credential
final credential = GoogleAuthProvider.credential(
accessToken: googleAuth.accessToken,
idToken: googleAuth.idToken,
);
// Sign in to Firebase with the Google credential
await _auth.signInWithCredential(credential);
} catch (e) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Sign in failed: ${e.toString()}')),
);
} finally {
if (mounted) {
setState(() {
_isLoading = false;
});
}
}
}
Future<void> _signOut() async {
try {
setState(() {
_isLoading = true;
});
await Future.wait([
_auth.signOut(),
_googleSignIn.signOut(),
]);
} catch (e) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Sign out failed: ${e.toString()}')),
);
} finally {
if (mounted) {
setState(() {
_isLoading = false;
});
}
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
// Show user info if logged in
StreamBuilder<User?>(
stream: _auth.authStateChanges(),
builder: (context, snapshot) {
if (snapshot.hasData) {
final user = snapshot.data!;
return Column(
children: [
CircleAvatar(
backgroundImage: user.photoURL != null
? NetworkImage(user.photoURL!)
: null,
radius: 40,
child: user.photoURL == null
? const Icon(Icons.person, size: 40)
: null,
),
const SizedBox(height: 16),
Text(user.displayName ?? 'User'),
Text(user.email ?? ''),
const SizedBox(height: 16),
ElevatedButton(
onPressed: _isLoading ? null : _signOut,
child: _isLoading
? const SizedBox(
width: 20,
height: 20,
child: CircularProgressIndicator(strokeWidth: 2),
)
: const Text('Sign Out'),
),
],
);
}
return ElevatedButton.icon(
onPressed: _isLoading ? null : _signInWithGoogle,
icon: _isLoading
? const SizedBox(
width: 20,
height: 20,
child: CircularProgressIndicator(strokeWidth: 2),
)
: Image.network(
'https://developers.google.com/identity/images/g-logo.png',
height: 24,
),
label: const Text('Sign in with Google'),
);
},
),
],
),
),
);
}
} |
@SelaseKay I made several tests and: Moving FirebaseAuth.instance.authStateChanges() before second initialization cause that this event triggers once. Unfortunately right after second init will trigger it stops receiving any events for example when user logs out. It seems that calling Firebase.initializeApp brokes previous calls silently is whole app. |
Hi @centy, you are right. The second initialization within the isolate seems to interrupt |
Hi @centy, I've made some changes to the example I shared earlier. Kindly try it out to see if it resolves your issue import 'dart:async';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_auth_example/firebase_options.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:flutter/material.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
unawaited(
compute(
(args) async {
final token = args['token']! as RootIsolateToken;
BackgroundIsolateBinaryMessenger.ensureInitialized(token);
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
await Future.delayed(const Duration(seconds: 200));
},
{
'token': RootIsolateToken.instance,
},
),
);
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final FirebaseAuth _auth = FirebaseAuth.instance;
final GoogleSignIn _googleSignIn = GoogleSignIn();
bool _isLoading = false;
Future<void> _signInWithGoogle() async {
try {
setState(() {
_isLoading = true;
});
final GoogleSignInAccount? googleUser = await _googleSignIn.signIn();
if (googleUser == null) return;
final GoogleSignInAuthentication googleAuth =
await googleUser.authentication;
final credential = GoogleAuthProvider.credential(
accessToken: googleAuth.accessToken,
idToken: googleAuth.idToken,
);
await _auth.signInWithCredential(credential);
} catch (e) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Sign in failed: ${e.toString()}')),
);
} finally {
if (mounted) {
setState(() {
_isLoading = false;
});
}
}
}
Future<void> _signOut() async {
try {
setState(() {
_isLoading = true;
});
await Future.wait([
_auth.signOut(),
_googleSignIn.signOut(),
]);
} catch (e) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Sign out failed: ${e.toString()}')),
);
} finally {
if (mounted) {
setState(() {
_isLoading = false;
});
}
}
}
@override
void initState() {
super.initState();
FirebaseAuth.instance.authStateChanges().listen((user) async {
print('Auth state changed: ${user?.uid}');
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
StreamBuilder<User?>(
stream: _auth.authStateChanges(),
builder: (context, snapshot) {
if (snapshot.hasData) {
final user = snapshot.data!;
return Column(
children: [
CircleAvatar(
backgroundImage: user.photoURL != null
? NetworkImage(user.photoURL!)
: null,
radius: 40,
child: user.photoURL == null
? const Icon(Icons.person, size: 40)
: null,
),
const SizedBox(height: 16),
Text(user.displayName ?? 'User'),
Text(user.email ?? ''),
const SizedBox(height: 16),
ElevatedButton(
onPressed: _isLoading ? null : _signOut,
child: _isLoading
? const SizedBox(
width: 20,
height: 20,
child:
CircularProgressIndicator(strokeWidth: 2),
)
: const Text('Sign Out'),
),
],
);
}
return ElevatedButton.icon(
onPressed: _isLoading ? null : _signInWithGoogle,
icon: _isLoading
? const SizedBox(
width: 20,
height: 20,
child: CircularProgressIndicator(strokeWidth: 2),
)
: Image.network(
'https://developers.google.com/identity/images/g-logo.png',
height: 24,
),
label: const Text('Sign in with Google'),
);
},
),
],
),
),
);
}
} |
Is there an existing issue for this?
Which plugins are affected?
Auth
Which platforms are affected?
Android
Description
We are using login via Google, user is able to login and all seems to work, however when app is closed and reopen, user is not logged in.
We follow exactly steps from here -> https://firebase.google.com/docs/auth/flutter/start
What is strange that in debug it works and remember current user, problem is only in release build.
Nothing interesting in logcat related auth or filebase, no errors.
Reproducing the issue
Just follow steps https://firebase.google.com/docs/auth/flutter/start,
Firebase Core version
3.10.1
Flutter Version
3.27.3
Relevant Log Output
Flutter dependencies
dependency_overrides:
shared_preferences_android: '2.4.0'
Replace this line with the contents of your `flutter pub deps -- --style=compact`.
Additional context and comments
No response
The text was updated successfully, but these errors were encountered: