Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
      });
     }
    }
   }
like image 931
Jakob Avatar asked Sep 13 '20 10:09

Jakob


People also ask

How do I add user data to firestore Flutter?

just follow the steps: call userSetup Function from onpress while passing the display name data. the below code will create new document using the currect users uuid in firestore in user collection and save the data.

How do you send OTP with Firebase in Flutter?

After making Firebase Project from Firebase console, and integrating it with Flutter application, you must enable the Phone sign up method first. For this go in Firebase console, open the Authentication tab from the left panel. Click on the Setup Sign up method and enable the Phone verification.


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

like image 148
pradyot1996 Avatar answered Sep 24 '22 14:09

pradyot1996


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;
  }
}
like image 40
Nuqo Avatar answered Sep 23 '22 14:09

Nuqo