Reputation: 3724
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;
}
Upvotes: 4
Views: 8746
Reputation: 265
FirebaseUser _user;
@override
void initState() {
super.initState();
_checkUser();
}
@override
Widget build(BuildContext context) {
if (_user == null) {
return AuthStatus.notSignedIn;
} else {
return AuthStatus.signedIn;
}
}
Future<void> _checkUser() async {
_user = await FirebaseAuth.instance.currentUser();
setState(() {});
}
Upvotes: 0
Reputation: 1763
Seems like you're watching the login playlist of Andrea Bizzotto, am I right?
I've passed through it too. The way I managed so that I could fix the error was change the position of auth.currentUser()
declaration. You probably have created your Auth auth
inside the StatelessWidget
.
Try to move the instance of Auth
from StatelessWidget
to your State
, right before your void initState()
.
And also replace your code so that you can access your Auth
from the State
. Like this:
@override
void initState() {
// TODO: implement initState
super.initState();
try {
auth.currentUser().then((userId) { //I've removed the 'widget.'
setState(() {
authStatus =
userId == null ? AuthStatus.notSignedIn : AuthStatus.signedIn;
});
});
} catch (e) {}
}
Once you did this, your code should not throw this error anymore.
Upvotes: 3
Reputation: 103421
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;
}
Upvotes: 5