'User' can't be assigned to the parameter type 'Future<User>' in FutureBuilder

Viewed 1212

I'm trying to determine if 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 seems 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 user already logged
            return Dashboard();
          }

          /// other way there is no user logged.
          return LoginScreen();
        });
  }

I'm getting an error in 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 not work... Currently using firebase_auth: 0.20 and firebase_core 0.7

2 Answers

This is because FirebaseAuth.instance.currentUser return User and FutureBuilder expect future, To fix this you have two options:

  • Use this syntax : future: Future.value(FirebaseAuth.instance.currentUser),, this will convert User to ```Future
  • Check if FirebaseAuth.instance.currentUser is null and return the convenient widget.

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

Related