Objective
I am trying to display the name of a currently logged in user in my flutter app screen. If no user is currently logged in from this device, then a blanck would appear. This name is stored in a String variable called userName
. Also, if a user is logged in, a boolean isSignedIn
variable will be set to true, else it’ll be false.
My code:
In the firebase_auth_methods.dart file I have the following code:
final FirebaseAuth _auth;
//STATE PERSISTANCE
Stream<User?> get authState => FirebaseAuth.instance.authStateChanges();
//GET USER
User get user => _auth.currentUser!;
In my account_screen.dart file I have the following code in Widget build():
final currUser = context.read<FirebaseAuthMethods>().user;
print(currUser);
if (!currUser.isAnonymous && currUser.phoneNumber == null) {
userName = currUser.email!;
isSignedIn = true;
}
if (currUser.phoneNumber != null) {
userName = currUser.phoneNumber!;
isSignedIn = true;
}
if (currUser.isAnonymous) {
isSignedIn = true;
}
if (currUser == null) {
userName = "Guest";
isSignedIn = false;
}
Issue faced:
However, I am unable to check for a possible null value of currUser
as I am receiving the warning: The operand can’t be null, so the condition is always false.
Try removing the condition, an enclosing condition, or the whole conditional statement.
When no user is logged in from this emulator AVD/device, navigating to the account_screen is returning Null check operator is used on a null value error.
I seem to understand why I am getting this error, but don’t know how to perform the required validation check for the null value of currUser
. This is my first time of trying my hand at Firebase Authentication, so please help me solve this problem.
2
Answers
in your class for user, create a getter for bool if user is empty or not.
the logic here is if user id, or uid is empty or equal to
''
, then there is no userand you can use it like this :
Remove the ‘!’ sign from the getter:
And now when you read the user with:
It will be nullable.
You got the error because you forced the user non-nullable with the !.