4
votes

I'm new to Flutter and really, really new to firebase.

I'm trying to create a user via the createUserWithEmailAndPasswordMethod. I've successfully created on, but I'm trying to improve it by allowing the user to enter the desired username and setting said username to the displayName attribute.

My code is as follows:

    _createUser() async {
UserUpdateInfo updateInfo = UserUpdateInfo();
updateInfo.displayName = _usernameController.text;

FirebaseUser user = await _auth
    .createUserWithEmailAndPassword(
  email: _emailController.text,
  password: _passwordController.text,
)
    .then((user) {
  user.updateProfile(updateInfo);
});
print('USERNAME IS: ${user.displayName}');
}

The problem is when I run the app it always throws this exception:

NoSuchMethodError: The getter 'displayName' was called on null.

Every time I debug the user variable keeps showing as null as well, even though the user is created and I can print the email and password!

I guess the problem is that Firebase user is null, but even if I move the print('USERNAME IS: ${user.displayName}'); to right after updateProfile the same happens.

Hope you guys can help! Thanks.

3

3 Answers

4
votes

You should not use await and then together. await is a substitute for then method.

_createUser() async {
await _auth
    .createUserWithEmailAndPassword(
  email: _emailController.text,
  password: _passwordController.text,
)
FirebaseUser user = await _auth.currentUser();

  UserUpdateInfo updateInfo = UserUpdateInfo();
  updateInfo.displayName = _usernameController.text;
  user.updateProfile(updateInfo);
  print('USERNAME IS: ${user.displayName}');
}
2
votes

So, what worked for me was this: I had to call the reload() method to get the new user information after the updateProfile(). After some changes the method looks like this:

  _createUser() async {
UserUpdateInfo updateInfo = UserUpdateInfo();
updateInfo.displayName = _usernameController.text;

await _auth
    .createUserWithEmailAndPassword(
  email: _emailController.text,
  password: _passwordController.text,
)
    .then((user) async {
  await user.updateProfile(updateInfo);
  await user.reload();
  FirebaseUser updatedUser = await _auth.currentUser();
  print('USERNAME IS: ${updatedUser.displayName}');
  Navigator.of(context).push(
    MaterialPageRoute<Map>(
      builder: (BuildContext context) {
        return Posts(_googleSignIn, updatedUser);
      },
    ),
  );
}).catchError((error) {
  print('Something Went Wrong: ${error.toString()}');
});
}
0
votes

If someone is still searching, this is the working solution in 2021.

UserCredential userCred = await _auth.createUserWithEmailAndPassword(email, password);

await userCred.user.updateProfile(displayName: "Your Name");