How can I add the displayName to the Firebase user? (Flutter/Dart)

Viewed 9043

I can save the email and the password with Firebase Authentication. I also save this information with Cloud Firestore. But how can I add and save the displayName after registering?

my code:

Future registerWithEmailAndPassword(String email, String password) async {
try {
  AuthResult result = await _auth.createUserWithEmailAndPassword(
      email: email, password: password);
  FirebaseUser user = result.user;

  // create a new document for the user with the uid
  await DatabaseService(uid: user.uid)
      .updateUserData('User', user.email, 'test.de/test.png', user.uid);
  return _userFromFirebaseUser(user);
} catch (e) {
  print(e.toString());
  return null;
}

}

the register form button:

onPressed: () async {
  if (_formKey.currentState.validate()) {
    setState(() => loading = true);
    dynamic result = await _auth
        .registerWithEmailAndPassword(
            email, password);
    if (result == null) {
      setState(() {
        error = 'Valid email, please';
        loading = false;
      });
     }
    }
   }
3 Answers

You can use updateProfile method given in the FirebaseUser class to update the name and photo url.

updateProfile({String displayName, String photoURL}).

For email you can use the different method updateEmail(String newEmail) which is a async method.

Or to save the username directly into the firestore, after successful login you can use 'set' method of the FirebaseFirestore to save email, password and the username.

Here's the code if you want to save the Username together with the email and password

final FirebaseAuth _auth = FirebaseAuth.instance; 

//register with email & password & save username instantly
Future registerWithEmailAndPassword(String name, String password, String email) async {
  try {
    UserCredential result = await _auth.createUserWithEmailAndPassword(email: email, password: password);
    User user = result.user;
    user.updateProfile(displayName: name); //added this line
    return _user(user);
  } catch(e) {
    print(e.toString());
    return null;
  }
}
late User userFirebase;
Future<UserCredential> userCredential =await //Your code signin or signup
await userCredential.then((UserCredential value)  {
userFirebase = value.user!;
});
await userFirebase.updateDisplayName(event.name);
Related