Home > OS >  Cannot get the currentUser's displayName with FirebaseAuth
Cannot get the currentUser's displayName with FirebaseAuth

Time:01-09

I have made a sign-in page, and a sign-up page with Firebase Authentication in Flutter and Dart.

After the sign up, I'm trying to retrieve the current user's displayName, however, when I try retrieving it, I seem to get not the current one, but the one that I signed up with before this one.

However, when I for example hot-restart the app, I get the current user's details just fine.

I try to retrieve the current user's displayName property with this code:

  static String? getUsername() {
    return FirebaseAuth.instance.currentUser?.displayName!;
  }

The way I call this, is I initialize a variable to store the username which I get from the method, on a different dart file, different from the signUp page I got. I also call this method in the initState() method.

This is how I sign-up the user and set the displayName:

  static void signUpUser(String username, String emailAddress, String password) async {
    try {
      final credential =
          await FirebaseAuth.instance.createUserWithEmailAndPassword(
        email: emailAddress,
        password: password,
      );
      // Here I set the displayName property
      await credential.user!.updateDisplayName(username);
    } on FirebaseAuthException catch (e) {
      if (e.code == 'weak-password') {} 
      else if (e.code == 'email-already-in-use') {}
    } catch (e) {}
  }

I tried to use the user.reload(), and FirebaseAuth.userChanges() functions, but these did not seem to fix my problem.

Maybe I'm trying to retrieve the displayName property wrong, what am I missing? I'm quite new to developing my own apps and working with Firebase.

CodePudding user response:

The Future that updateDisplayName returns completes when the call has been made to the underlying Firebase SDK. It does not automatically update the user profile in your application at that point though. That will only happen automatically once every hour (when the SDK refreshes the ID token on which that profile is based), or when the user signs out and in again.

To force a refresh of the profile from your application code outside of those automatic conditions, you can call reload() on the user object.

  • Related