How to get Facebook Profile Photo and Other Data In Flutter

Step 1: You need to setup a permission when creating an instance for Facebook login.

FacebookAuth.instance.login(permissions: ['email', 'public_profile']);

Step 2: After setting the permission, you can now get the Facebook data of the user easily by simply using the line of code below. You can follow this link Graph API User (facebook.com) to know the different syntax in getting users details.

final facebookUserData = FacebookAuth.instance.getUserData();
facebookUserData['name']; //to get the name of the FB account
facebookUserData['picture']['data']['url'];  //to get the profile picture of the FB account 

Sample Code:

facebookLogin();

void facebookLogin() async {
    // Trigger the sign-in flow
    await FacebookAuth.instance.login(
      permissions: ['email', 'public_profile']).then((facebookUser) async {
      if (facebookUser != null) {
        await FacebookAuth.instance.getUserData().then((facebookUserData) async {
          if(facebookUser.accessToken != null){

            String token = facebookUser.accessToken!.token;
            String id = facebookUserData['id'];
            String email = facebookUserData['email'];
            String name = facebookUserData['name'];
            String first_name = facebookUserData['first_name'];
            String last_name = facebookUserData['last_name'];
            String profilePicture = facebookUserData['picture']['data']['url'];
            print(token);
            print(id);
            print(name);
            print(email);
            print(first_name);
            print(last_name);
            print(profilePicture);

          }
          else {
            throw PlatformException(
                code: 'ERROR_MISSING_FACEBOOK_AUTH_TOKEN',
                message: 'Missing Facebook Auth Token');
          }
        });
      }
      else {
        throw PlatformException(
            code: 'ERROR_ABORTED_BY_USER', message: 'Sign in aborted by user');
      }
    });
  } 

References:
https://developers.facebook.com/docs/graph-api/reference/user/
https://www.youtube.com/watch?v=PweQbVgR9iI

Leave a Comment

Your email address will not be published. Required fields are marked *