Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to resolve this NoSuchMethodError in flutter firebase

I have this code which is supposed to return the userId. Problem is it returns null since the user is signed out.

@override
void initState() {
// TODO: implement initState
super.initState();
try {
  widget.auth.currentUser().then((userId) {
    setState(() {
     authStatus = userId == null ? AuthStatus.notSignedIn : AuthStatus.signedIn;
    });
  });
} catch (e) {}
}

This still throws an error even after wrapping a catch block around it. the error freezes my app Error:

Exception has occurred.
NoSuchMethodError: The getter 'uid' was called on null.
Receiver: null
Tried calling: uid

The method trying to be called is

Future<String> currentUser() async {
FirebaseUser user = await _firebaseAuth.currentUser();
return user.uid;
}
like image 213
Taio Avatar asked Jan 27 '23 13:01

Taio


1 Answers

Try this:

     widget.auth.currentUser().then((userId) {
        setState(() {
         authStatus = userId == null ? AuthStatus.notSignedIn : AuthStatus.signedIn;
        });
      }).catchError((onError){
        authStatus = AuthStatus.notSignedIn;
      });

Update If the firebaseAuth return null you can't use uid property from user because it's null.

    Future<String> currentUser() async {
      FirebaseUser user = await _firebaseAuth.currentUser();
      return user != null ? user.uid : null;
    }
like image 87
diegoveloper Avatar answered Feb 13 '23 05:02

diegoveloper