Search code examples
flutterfirebasefirebase-authenticationgoogle-signin

flutter google_sign_in only opens login window (popup) for the first time


I am using the official google_sign_in package for signing the user in to my Flutter app. When the user wants to sign in for the first time, a popup is opened to select from a list of available accounts, but when the user logs out and wants to sign in again, it automatically signs the user in to the previous account, thus not opening the login popup.

I want the popup to open every time so that the user can select a different Google account.

Here's the code I use:

Future<UserCredential> signInWithGoogle() async {
    // Trigger the authentication flow
    final GoogleSignInAccount? googleUser = await GoogleSignIn().signIn();

    // Obtain the auth details from the request
    final GoogleSignInAuthentication? googleAuth =
        await googleUser?.authentication;

    // Create a new credential
    final credential = GoogleAuthProvider.credential(
      accessToken: googleAuth?.accessToken,
      idToken: googleAuth?.idToken,
    );

    // Once signed in, return the UserCredential
    return await auth.signInWithCredential(credential);
  }

Solution

  • The solution is simple. You can just use signOut function.

    Here is the code:

        Future<UserCredential> signInWithGoogle() async {
            // Trigger the authentication flow
            final GoogleSignInAccount? googleUser = await GoogleSignIn().signIn();
        
            // Obtain the auth details from the request
            final GoogleSignInAuthentication? googleAuth =
                await googleUser?.authentication;
        
            // Create a new credential
            final credential = GoogleAuthProvider.credential(
              accessToken: googleAuth?.accessToken,
              idToken: googleAuth?.idToken,
            );
    
            // Once signed in, return the UserCredential
          final UserCredential userCredential =
              await auth.signInWithCredential(credential);
    
          final GoogleSignInAccount? user = await GoogleSignIn().signOut(); // <-- add this code here
    
          return userCredential;
      }
    

    After you get the necessary user information through GoogleSignIn().signIn() and do something, you can apply GoogleSignIn().signOut() to remove existing user information cache.

    Or, you can do it by calling and defining signout function.

      Future<void> signOut() async {
        try {
          await GoogleSignIn().signOut();
        } catch (e) {
          debugPrint('Error signing out. Try again.');
        }
      }