Home > OS >  The method 'then' isn't defined for the type 'User'(with asynchronous funct
The method 'then' isn't defined for the type 'User'(with asynchronous funct

Time:06-10

I am working on this app and keep getting this error. No solutions have worked so far.

_initialize() async{

SharedPreferences prefs = await SharedPreferences.getInstance();
bool loggedIn = prefs.getBool(LOGGED_IN) ?? false;
if(!loggedIn){
  _status = Status.Unauthenticated;
}else{
  await auth.currentUser.then((User currentUser) async{
    _user = currentUser;
    _status = Status.Authenticated;
    _userModel = await _userServices.getUserById(currentUser.uid);
  });

}

CodePudding user response:

Because the property currentUser is not a Future, it gives you the value immediately, so you can't wait for it and you don't even have to.

So the else block should be:

else {
    _user = auth.currentUser;
    _status = Status.Authenticated;
    _userModel = await _userServices.getUserById(auth.currentUser.uid);
}

CodePudding user response:

NEVER ever use a .then

With a high probability, from my experience, if you are using a future.then in your code, you are doing something wrong.

After this premise:

You probably don't understand what you are doing, here some comments and a proper formatting for you to understand better.

//It is a good practice to always mark the return type 
void _initialize() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    bool loggedIn = prefs.getBool(LOGGED_IN) ?? false;
    if(!loggedIn){
        _status = Status.Unauthenticated;
    }else{
        //You are awaiting the future currentUser. But in fact, it isn't a future at all, as you can read [here][1]
        await auth.currentUser.then((User currentUser) async{
            _user = currentUser;
            _status = Status.Authenticated;
            _userModel = await _userServices.getUserById(currentUser.uid);
        });
    }
}

The code you should use should be something like this:

//It is a good practice to always mark the return type 
void _initialize() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    bool loggedIn = prefs.getBool(LOGGED_IN) ?? false;
    if(!loggedIn){
        _status = Status.Unauthenticated;
    }else{
        _user = auth.currentUser;
        _status = Status.Authenticated;
        _userModel = await _userServices.getUserById(auth.currentUser.uid);
    }
}

1: https://firebase.flutter.dev/docs/auth/usage/

  • Related