I am trying to get the user details after the user signs with google using firebase in flutter. here is code I have and it successfully signs the user in, but when I access the details it gives me this message when I hover over the red line - Error - The property 'username' can't be unconditionally accessed because the receiver can be 'null'
Future<User?> signInWithGoogle() async {
FirebaseAuth auth = FirebaseAuth.instance;
User? user;
final GoogleSignInAccount? googleUser = await GoogleSignIn().signIn();
if (googleUser != null) {
final GoogleSignInAuthentication googleAuth = await googleUser.authentication;
final AuthCredential credential = GoogleAuthProvider.credential(
accessToken: googleAuth.accessToken,
idToken: googleAuth.idToken,
);
try {
final UserCredential userCredential = await auth.signInWithCredential(credential);
final user = userCredential.additionalUserInfo.username;
print(user);
} on FirebaseAuthException catch (e) {
if (e.code == 'account-exists-with-different-credential') {
} else if (e.code == 'invalid-credential') {
}
} catch (e) {
}
}
return user;
}
}
Here is the screenshot of the red line appearing under the user variable -
How do get all the details of the logged in user including the session info?
The reason you see the error message is quite goode explained in it: The value username
can't be used like that bevause the owner of that value can be null
so yuo would need to check first if it is null or not.
Ti get the user data use the onAuthStateChanged
listener:
FirebaseAuth.instance
.authStateChanges()
.listen((User? user) {
if (user == null) {
print('User is currently signed out!');
} else {
print('User is signed in!');
}
});
It would make the auth state management much easier for you and generalise the workflow for any provider you use. You can also capture with it a logout