facebookAuthCredential.idToken is null in Flutter

1.5k Views Asked by At

I successfully integrated facebook login in android and ios, I also getting facebook access token on login but getting null in token id. Below is the code

  Future<UserCredential> signInWithFacebook() async {
    // Trigger the sign-in flow
    final LoginResult loginResult = await FacebookAuth.instance.login();

    // Create a credential from the access token
    final OAuthCredential facebookAuthCredential =
        FacebookAuthProvider.credential(loginResult.accessToken!.token);
    print(facebookAuthCredential.idToken); //Here getting null

    // Once signed in, return the UserCredential
    return FirebaseAuth.instance.signInWithCredential(facebookAuthCredential);
  }
1

There are 1 best solutions below

4
On BEST ANSWER

You won't get an idToken at this point with Facebook authentication flow, only accessToken. Use the following code skeleton to manage Facebook sign-in and evaluate the results at specific lines with breakpoints:

Future<UserCredential> signInWithFacebook() async {
  final LoginResult loginResult = await FacebookAuth.instance.login();

  if (loginResult.status == LoginStatus.success) {
    final AccessToken accessToken = loginResult.accessToken!;
    final OAuthCredential credential =
        FacebookAuthProvider.credential(accessToken.token);
    try {
      return await FirebaseAuth.instance.signInWithCredential(credential);
    } on FirebaseAuthException catch (e) {
      // manage Firebase authentication exceptions
    } catch (e) {
      // manage other exceptions
    }
  } else {
      // login was not successful, for example user cancelled the process
  }
}

Then you can call this function with await, and once the future is completed, you can access user data:

final userCredential = await signInWithFacebook();
if (userCredential != null) {
    // here you will have your Firebase user in:
    // userCredential.user
    final idToken = userCredential.user!.getIdToken();
}