In flutter how to get current user logged in from

2019-02-25 14:11发布

问题:

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"

回答1:

I don't know Flutter well enough yet to be sure, but from your error message, I think this should fix the error

someMethod() async {
  FirebaseUser user = await FirebaseAuth.instance.currentUser();
  print(user.uid);    


回答2:

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 flutter