In flutter how to get current user logged in from the cache maintained by firebase for signin type of email and password

Viewed 18818

I am able to signin with user in my authentication, but how to get current user aid in dart flutter.

I am trying in this way

FirebaseUser user = FirebaseAuth.instance.currentUser;
print(user.uid);

but showing error as

A value of type'()-> Future can't be assigned to a variable of type firebaseuser"

4 Answers

Here is a solution that worked for me. I too had the same problem, but I managed to overcome by doing this. Here is my code snippet

String accountStatus = '******';
FirebaseUser mCurrentUser;
FirebaseAuth _auth;

@override
void initState() {
  super.initState();
  _auth = FirebaseAuth.instance;
  _getCurrentUser();
  print('here outside async');
}

_getCurrentUser () async {
  mCurrentUser = await _auth.currentUser();
  print('Hello ' + mCurrentUser.displayName.toString());
  setState(() {
    mCurrentUser != null ? accountStatus = 'Signed In' : 'Not Signed In';
  });
}

In my StatefulWidget class's build method I have a text widget with 'accountStatus' that shows that the user is logged in or not. This async _getCurrentUser method get the user from the FirebaseAuth and repaints the account status variable on the screen; Once you signIn with email and password then the user is easily obtained from the async method. Hope this serves the question Note that this works even when the internet is off. In that case 'mCurrentUser' is obtained from the Firebase cache.

//dart


String userId = "";

  @override
  void initState() {
    super.initState();
    widget.auth.getCurrentUser().then((user) { //widget.auth => 'Auth auth = new Auth();' 
      setState(() {
        if (user != null) {
          userId = user?.uid;

          print(userId);
        }
      });
    });
  }
  
  
  //in auth file
  Future<FirebaseUser> getCurrentUser() async {
    FirebaseUser user = await firebaseAuth.currentUser();
    return user;
  }
  
  

that should help

FirebaseUser currentUser = await FirebaseAuth.instance.currentUser(); This will simply give you the currentUser already authenticated

Related