flutterfirebase-authenticationgoogle-signin

Logged in but cant get the user data


I have added google sign in in my flutter web project, it's success to do login when i first run the code. But after do refresh, or hot restart, the currentUser data will be null.

loginWithGoogle(context) async {
    try {
      if (kIsWeb) {
        googleSignIn = GoogleSignIn(
            clientId:
                'client-id.apps.googleusercontent.com');

        GoogleSignInAccount? googleSignInAccount = kIsWeb
            ? await (googleSignIn.signInSilently())
            : await (googleSignIn.signIn());

        if (kIsWeb && googleSignInAccount == null) {
          googleSignInAccount = await (googleSignIn.signIn());
        }
        googleSignIn.onCurrentUserChanged
            .listen((GoogleSignInAccount? account) {
          // save login info
        });
        bool isSigned = await googleSignIn.isSignedIn();
        if (isSigned) {
          // save login info when user has logged in
          final User? currentUser = auth.currentUser;
          print(currentUser?.email);
        }
      } else {
        // handle login for android device
    } catch (e) {
      Get.snackbar('Firebase error', e.toString());
    }
  }

It's function is used for web and android device, in android is can run smoothly, but when i run in the chrome-web it's success to get user when i first running the code, but after do hot refresh, it cant get the user data.

When calling isSignedIn() it return true value, but when call the currentUser?.email it return null

can somebody tell me where need to fix?


Solution

  • That is the expected behavior: while Firebase Authentication automatically restores the user on a reload, that requires it to call to the servers (to check for example of the account has been disabled) and that call likely hasn't complete yet when you access auth.currentUser.

    The correct way to pick up the current user is to listen to the authStateChanges stream as shown in this example in the documentation on getting the current user:

    FirebaseAuth.instance
      .authStateChanges()
      .listen((User? user) {
        if (user != null) {
          print(user.uid);
        }
      });
    

    If you want to show this in the UI, you'll want to use a StreamBuilder and set its property to FirebaseAuth.instance.authStateChanges().