TonyWyomy
TonyWyomy

Reputation: 610

show display name after signUp

I have a flutter firebase createUserWithEmailAndPassword function with the displayName update. display name prints normally at the moment of fb user creation. After signup MainPage loads with the users email and displayName. But displayName returns null value error. If I delete displayName from the MainPage - all works fine. If I reload app, it works fine. When I login, it works fine. It can't pass the displayName at the moment of signup only. Where I am wrong?

class AuthServiceProvider extends ChangeNotifier {
  final auth.FirebaseAuth _firebaseAuth = auth.FirebaseAuth.instance;
  final googleSingIn = GoogleSignIn();

  UserModel? _userFromFirebase(auth.User? user) {
    if (user == null) {
      return null;
    }
    return UserModel(
      user.displayName,
      user.uid,
      user.email,
    );
  }

  Stream<UserModel?>? get user {
    return _firebaseAuth.authStateChanges().map(_userFromFirebase);
  }

 
  Future<UserModel?> createUserWithEmailAndPassword(
    String name,
    String email,
    String password,
  ) async {
    try {
      final userCred = await _firebaseAuth.createUserWithEmailAndPassword(
        email: email,
        password: password,
      );

      auth.User? firebaseUser = _firebaseAuth.currentUser;

      if (firebaseUser != null) {
        await firebaseUser.updateDisplayName(name);
        await firebaseUser.reload();
        firebaseUser = _firebaseAuth.currentUser;
      }
       print('FIREBASE USER IS $firebaseUser');
      

      return _userFromFirebase(firebaseUser);
    } catch (e) {
      print(e.toString());
      return null;
    }
  }
}

Upvotes: 1

Views: 946

Answers (2)

TonyWyomy
TonyWyomy

Reputation: 610

As usually the solution is very simple if you think a little bit. As all this is through the firebase auth, at the main page loading I just grab the firebase user with its display name that is saved in FB both for GoogleSignIn and createUserWithEmailAndPassword (required at registration)

import 'package:firebase_auth/firebase_auth.dart' as auth;

final auth.FirebaseAuth _firebaseAuth = auth.FirebaseAuth.instance;
    final String firebaseUser =
        _firebaseAuth.currentUser!.displayName ?? 'Unknown user';

Upvotes: 2

If your class were to extend either StatelessWidget or StatefulWidget, then all you'd have to do is to pass the data (displayName) between the screens.

This is not an answer but a suggestion:

  1. You should try changing the ChangeNotifier to a StatefulWidget and pass the data between screens...
  2. You could also setup an Authentication class that will hold all these Future methods so that these calls can be reusable in your code. With this method, all you have to do is to call the specific function and give its required parameters.

Upvotes: 1

Related Questions