I am building an app using Flutter and Firebase. I am trying to create a user profile on their first login to the app. I am using the Google sign-in method provided by Firebase authentication.
This is my code for the same:
void _handleGoogleSignIn() async {
try {
GoogleAuthProvider googleAuthProvider = GoogleAuthProvider();
UserCredential userCredential =
await _auth.signInWithProvider(googleAuthProvider);
User? user = userCredential.user;
// check if user pf exists
if (user != null) {
DocumentSnapshot userDoc = await FirebaseFirestore.instance
.collection("users")
.doc(user.uid)
.get();
// if not there, then create
if (!userDoc.exists) {
await FirebaseFirestore.instance
.collection("users")
.doc(user.uid)
.set(
{
"photoUrl": user.photoURL,
"displayName": user.displayName,
"email": user.email,
},
);
}
}
} catch (e) {
showDialog(
context: context,
builder: (context) {
return AlertDialog(
content: Text(e.toString()),
);
},
);
}
}
I am storing displayName
, photoUrl
, email
, and other fields (still thinking). But on the Firestore window, it shows that the document was stored with displayName
set to null
.
So what am I doing wrong, and what is the fix?
2
Answers
The Display Name will be null when you create the user, You need to update it adter creating the user
Since you’re using Firebase Authentication with Google, most likely you should read the username field that exists inside the AdditionalUserInfo class. So in code, it should be something like this: