'User is turning null when refreshing chrome page flutter web firebase
I can properly login and signup with Firebase Auth in web. When I hot reload the page, user info maintain and they stay logged in. But, it I refresh the page, using chrome, user turns null and I need to login again.
Auth service:
static Future<User?> signInUsingEmailPassword(
{required String email,
required String password,
required BuildContext context}) async {
FirebaseAuth auth = FirebaseAuth.instance;
User? user;
try {
UserCredential userCredential = await auth.signInWithEmailAndPassword(
email: email,
password: password,
);
user = userCredential.user;
} on FirebaseAuthException catch (e) {
if (e.code == 'user-not-found') {
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('Usuário não encontrado.'), duration: Duration(seconds: 4),));
} else if (e.code == 'wrong-password') {
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('Senha inválida.'), duration: Duration(seconds: 4),));
}
}
return user;
}
Main.dart:
body: FutureBuilder(future: _initialization, builder: (context, snapshot){
if(snapshot.hasError){
return const Center(child: Text('Houve algum erro. Tente novamente'),);
}
if(snapshot.connectionState == ConnectionState.done){
print('usuário: $user');
print('emailVErified: ${user?.emailVerified}');
if(user == null || user?.emailVerified == false){
return const AuthenticationPage();
}
if (user != null && user?.emailVerified == true) {
return const HomePage();
}
}
return const Center(child: CircularProgressIndicator(),);
},),
Solution 1:[1]
This is the expected behavior. Firebase stores the user credentials when they sign in, and then restores them when the page (or app) reloads. This requires that it call to the server however, for example to check if the account was disabled, and while this call is going on your code continues to run and currentUser is null.
To properly pick up when the sign-in is restored (or it failed to restore), you'll need to implement an auth state listener, as shown in the first snippet in the documentation on getting the current user:
FirebaseAuth.instance
.authStateChanges()
.listen((User? user) {
if (user != null) {
print(user.uid);
}
});
So you can listen to the auth state, or you could wrap it in a StreamBuilder in your build method to have your UI respond to all auth state changes.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Frank van Puffelen |
