signInWithGoogle method

Future<FirebaseAuthenticationResult> signInWithGoogle({
  1. String? webLoginHint,
})

Authenticates a user through Firebase using Google Provider.

Supported platforms:

  • Android
  • iOS
  • Web

Implementation

Future<FirebaseAuthenticationResult> signInWithGoogle(
    {String? webLoginHint}) async {
  try {
    UserCredential userCredential;

    /// On the web, the Firebase SDK provides support for automatically
    /// handling the authentication flow.
    if (kIsWeb) {
      GoogleAuthProvider googleProvider = GoogleAuthProvider();
      googleProvider.setCustomParameters(
          {'login_hint': webLoginHint ?? 'user@example.com'});

      userCredential = await FirebaseAuth.instance.signInWithPopup(
        googleProvider,
      );
    }

    /// On native platforms, a 3rd party library, like GoogleSignIn, is
    /// required to trigger the authentication flow.
    else {
      final GoogleSignInAccount? googleSignInAccount =
          await _googleSignIn.signIn();
      if (googleSignInAccount == null) {
        log?.i('Process is canceled by the user');
        return FirebaseAuthenticationResult.error(
          errorMessage: 'Google Sign In has been canceled by the user',
          exceptionCode: 'canceled',
        );
      }
      final GoogleSignInAuthentication googleSignInAuthentication =
          await googleSignInAccount.authentication;

      final AuthCredential credential = GoogleAuthProvider.credential(
        accessToken: googleSignInAuthentication.accessToken,
        idToken: googleSignInAuthentication.idToken,
      );

      userCredential = await _signInWithCredential(credential);
    }

    // Link the pending credential with the existing account
    if (_pendingCredential != null) {
      await userCredential.user?.linkWithCredential(_pendingCredential!);
      _clearPendingData();
    }

    return FirebaseAuthenticationResult(
      user: userCredential.user,
      additionalUserInfo: userCredential.additionalUserInfo,
    );
  } on FirebaseAuthException catch (e) {
    log?.e(e);
    return FirebaseAuthenticationResult.error(
      errorMessage: getErrorMessageFromFirebaseException(e),
      exceptionCode: e.code,
    );
  } catch (e) {
    log?.e(e);
    return FirebaseAuthenticationResult.error(errorMessage: e.toString());
  }
}