signInWithFacebook method

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

Authenticates a user through Firebase using Facebook Provider.

Supported platforms:

  • Android
  • iOS
  • Web

Implementation

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

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

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

    /// On native platforms, a 3rd party library, like FacebookSignIn, is
    /// required to trigger the authentication flow.
    else {
      final LoginResult facebookLoginResult =
          await FacebookAuth.instance.login();
      if (facebookLoginResult.status == LoginStatus.cancelled) {
        log?.i('Process is canceled by the user');
        return FirebaseAuthenticationResult.error(
          errorMessage: 'Facebook Sign In has been canceled by the user',
          exceptionCode: 'canceled',
        );
      } else if (facebookLoginResult.status == LoginStatus.failed) {
        log?.i('Login failed with error: ${facebookLoginResult.message}');
        return FirebaseAuthenticationResult.error(
          errorMessage:
              'Facebook Sign In has failed with error: ${facebookLoginResult.message}',
          exceptionCode: 'failed',
        );
      }

      final OAuthCredential facebookAuthCredential =
          FacebookAuthProvider.credential(
              facebookLoginResult.accessToken!.token);

      userCredential = await _signInWithCredential(facebookAuthCredential);
    }

    // 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());
  }
}