Search code examples
firebaseflutterdartfirebase-authentication

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


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;
      });
     }
    }
   }

Solution

  • 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.