Reputation: 67
I'm trying to determine if the user is logged in (Flutter Firebase) using FirebaseAuth.instance.currentUser, and then return LoginScreen or Dashboard, but getting an error. I tried to write code based on instructions from FirebaseFlutter, but those seem to be deprecated...
Widget build(BuildContext context) {
return FutureBuilder<User>(
future: FirebaseAuth.instance.currentUser,
builder: (BuildContext context, AsyncSnapshot<User> snapshot) {
if (snapshot.hasData) {
User user = snapshot.data;
/// is because there is a user already logged
return Dashboard();
}
/// Other way there is no user logged.
return LoginScreen();
});
}
I'm getting an error in the 3rd line future: ...
that stands for The argument type 'User' can't be assigned to the parameter type 'Future<User>'
. Please may anyone explain to me how should I do this, and what I'm doing wrong?
I tried to pass that in function ()=>
but it still does not work...
Currently using firebase_auth: 0.20 and firebase_core 0.7
Upvotes: 3
Views: 2134
Reputation: 2862
This is because FirebaseAuth.instance.currentUser
return User
and FutureBuilder
expect future
, To fix this you have two options:
future: Future.value(FirebaseAuth.instance.currentUser),
, this will convert User
to ```FutureFirebaseAuth.instance.currentUser
is null
and return the convenient widget.Upvotes: 13
Reputation: 8383
FirebaseAuth.instance.currentUser
is not a Future. It directlty returns the current User
if they are currently signed-in, or null
if not.
Try this:
Widget build(BuildContext context) {
return FirebaseAuth.instance.currentUser != null ? Dashboard() : LoginScreen();
}
Though, be aware that it might be null first when you refresh the page.
ref: https://pub.dev/documentation/firebase_auth/latest/firebase_auth/FirebaseAuth/currentUser.html
Instead, you may have a look at Stream<User> authStateChanges ()
.
Ref: https://pub.dev/documentation/firebase_auth/latest/firebase_auth/FirebaseAuth/authStateChanges.html
Upvotes: 5