lecle_flutter_facebook_login
A Flutter plugin for using the native Facebook Login SDKs on Android and iOS. Migrate and update from flutter_facebook_login plugin.
Installation
To get things up and running, you'll have to declare a pubspec dependency in your Flutter project. Also some minimal Android & iOS specific configuration must be done, otherwise your app will crash.
On your Flutter project
See the installation instructions on pub.
Android
This assumes that you've done the "Associate Your Package Name and Default Class with Your App" and "Provide the Development and Release Key Hashes for Your App" in the Facebook Login documentation for Android site.
After you've done that, find out what your Facebook App ID and Facebook App Client Token are. You can find your Facebook App ID in your Facebook App's dashboard in the Facebook developer console. Your Facebook App Client Token can be found in Facebook developer console => Settings => Advanced => Application code.
Once you have the Facebook App ID and Facebook App Client Token figured out, you'll have to do two things.
First, copy-paste the following to your strings resource file. If you don't have one, just create it.
<your project root>/android/app/src/main/res/values/strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Your App Name here.</string>
<!-- Replace "000000000000" with your Facebook App ID here. -->
<string name="facebook_app_id">000000000000</string>
<!--
Replace "000000000000" with your Facebook App ID here.
**NOTE**: The scheme needs to start with `fb` and then your ID.
-->
<string name="fb_login_protocol_scheme">fb000000000000</string>
<string name="facebook_client_token">Your App Client Token here.</string>
</resources>
Then you'll just have to copy-paste the following to your Android Manifest:
<your project root>/android/app/src/main/AndroidManifest.xml
<meta-data android:name="com.facebook.sdk.ApplicationId"
android:value="@string/facebook_app_id"/>
<meta-data android:name="com.facebook.sdk.ClientToken"
android:value="@string/facebook_client_token" />
<activity android:name="com.facebook.FacebookActivity"
android:configChanges=
"keyboard|keyboardHidden|screenLayout|screenSize|orientation"
android:label="@string/app_name" />
<activity
android:name="com.facebook.CustomTabActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="@string/fb_login_protocol_scheme" />
</intent-filter>
</activity>
- Enable express login for Android platform
If your app support Android 11, add the xml tag below into your /app/manifest/AndroidManifest.xml
<queries> <package android:name="com.facebook.katana" /> </queries>
Done!
iOS
Open Xcode and change your deployment info to 11.0
or you can change it inside the Podfile of your app iOS folder.
This assumes that you've done the "Register and Configure Your App with Facebook" step in the the Facebook Login documentation for iOS site. (Note: you can skip "Step 2: Set up Your Development Environment" and "Step 5: Connect Your App Delegate").
After you've done that, find out what your Facebook App ID and Facebook App Client Token are. You can find your Facebook App ID in your Facebook App's dashboard in the Facebook developer console. Your Facebook App Client Token can be found in Facebook developer console => Settings => Advanced => Application code.
Once you have the Facebook App ID and Facebook App Client Token figured out, then you'll just have to copy-paste the following to your
Info.plist file, before the ending </dict></plist>
tags.
(NOTE: If you are using this plugin in conjunction with for example google_sign_in
plugin, which also requires you to add CFBundleURLTypes
key into Info.plist file, you need to merge them together).
<your project root>/ios/Runner/Info.plist
<key>CFBundleURLTypes</key>
<array>
<!--
<dict>
... Some other CFBundleURLTypes definition.
</dict>
-->
<dict>
<key>CFBundleURLSchemes</key>
<array>
<!--
Replace "000000000000" with your Facebook App ID here.
**NOTE**: The scheme needs to start with `fb` and then your ID.
-->
<string>fb000000000000</string>
</array>
</dict>
</array>
<key>FacebookAppID</key>
<!-- Replace "000000000000" with your Facebook App ID here. -->
<string>000000000000</string>
<key>FacebookDisplayName</key>
<!-- Replace "YOUR_APP_NAME" with your Facebook App name. -->
<string>YOUR_APP_NAME</string>
<key>FacebookClientToken</key>
<!-- Replace "YOUR_APP_CLIENT_TOKEN" with your Facebook App CLIENT TOKEN. -->
<string>YOUR_APP_CLIENT_TOKEN</string>
<key>LSApplicationQueriesSchemes</key>
<array>
<string>fbapi</string>
<string>fb-messenger-share-api</string>
<string>fbauth</string>
<string>fbauth2</string>
<string>fbshareextension</string>
<string>fbapi20130214</string>
<string>fbapi20130410</string>
<string>fbapi20130702</string>
<string>fbapi20131010</string>
<string>fbapi20131219</string>
<string>fbapi20140410</string>
<string>fbapi20140116</string>
<string>fbapi20150313</string>
<string>fbapi20150629</string>
<string>fbapi20160328</string>
</array>
Done!
App Tracking Transparency
Since iOS 14.5 all apps that want to track the user activity to share data across others providers after the login process needs to request the AppTrackingTransparency permission.
If your app need to do this you have to complete the steps below:
- Add the
FacebookAutoLogAppEventsEnabled
key into theInfo.plist
file and set the value tofalse
.
<key>FacebookAutoLogAppEventsEnabled</key>
<false/>
- Add
NSUserTrackingUsageDescription
key into your project'sInfo.plist
file.
<key>NSUserTrackingUsageDescription</key>
<string>Your reason, why you want to track the user</string>
- You can ask this permission using permission_handler plugin.
final status = await Permission.appTrackingTransparency.request();
if (status == PermissionStatus.granted) {
await facebookLogin.setAutoLogAppEventsEnabled(true);
print('Is auto log app events enabled ::: ${await facebookLogin.isAutoLogAppEventsEnabled}');
}
How do I use it?
The library tries to closely match the native Android & iOS login SDK APIs where possible.
Since sample code is worth more than one page of documentation, here are the usual cases covered:
import 'package:lecle_flutter_facebook_login/lecle_flutter_facebook_login.dart';
final facebookLogin = LecleFlutterFacebookLogin();
final result = await facebookLogin.logIn();
switch (result.status) {
case FacebookLoginStatus.loggedIn:
_sendTokenToServer(result.accessToken.token);
_showLoggedInUI();
break;
case FacebookLoginStatus.cancelledByUser:
_showCancelledMessage();
break;
case FacebookLoginStatus.error:
_showErrorOnUI(result.errorMessage);
break;
}
You can also change the visual appearance of the login dialog. For example:
// Let's force the users to login using the login dialog based on WebViews. Yay!
facebookLogin.loginBehavior = FacebookLoginBehavior.webOnly;
// Or using the provided method
facebookLogin.setLoginBehavior(FacebookLoginBehavior.webOnly);
The logIn() method will provide three basic login permissions are: email, openid and public_profile
. If you want to add more permissions you
can check the Facebook's document here.
Check if user is signed in
Simply call the isLoggedIn
getter from the LecleFlutterFacebookLogin's object:
_facebookSignIn.isLoggedIn.then((isLoggedIn) {
if (isLoggedIn) {
print('User logged in');
} else {
print('User is not login yet');
}
});
Getting the Facebook profile of a signed in user
You can use two provided methods.
- facebookLogin.getUserData(fields: ''): The response of the method now will be converted directly into a
Map
and you don't need to decode the result to get the data.
_facebookSignIn.getUserData(
fields: 'id,name,first_name,last_name, email,middle_name,name_format,picture,short_name',
).then((value) {
print('User data ::: $value');
});
- facebookLogin.getUserDataAndMapToModel(fields: ''): This method will convert the Map data into a
FacebookUserProfile
's object which help you the get user profile data easier using the class properties.
_facebookSignIn.getUserDataAndMapToModel(
fields: 'id,'
'name,'
'first_name,'
'last_name,'
'email,'
'middle_name,'
'name_format,'
'picture,'
'short_name',
).then((value) {
print('User data model ::: ${value?.toJson()}');
});
Express login for Android platform
Express Login helps users log in with their Facebook account across devices and platforms. If a person has logged into your app before on any platform, you can use Express Login to log them in with their Facebook account on Android, instead of asking for them to select a login method, which sometimes resulted in creating duplicate accounts or even failing to log in at all.
final facebookLogin = LecleFlutterFacebookLogin();
final result = await facebookLogin.expressLogin();
switch (result.status) {
case FacebookLoginStatus.loggedIn:
_sendTokenToServer(result.accessToken.token);
_showLoggedInUI();
break;
case FacebookLoginStatus.cancelledByUser:
_showCancelledMessage();
break;
case FacebookLoginStatus.error:
_showErrorOnUI(result.errorMessage);
break;
}
Get current Facebook access token
Simply call currentAccessToken
getter from the LecleFlutterFacebookLogin
's object:
_facebookSignIn.currentAccessToken.then((accessToken) {
print('Current access token ::: ${accessToken?.toJson()}');
});
Logout
Simply call the logout()
method from LecleFlutterFacebookLogin
's object:
_facebookSignIn.logOut();
Reauthorize data access
Requests user's permission to reauthorize application's data access, after it has expired due to inactivity. Use this method when you need to reauthorize your app's access to user data via the Graph API. You should only call this after access has expired. You should provide as much context to the user as possible as to why you need to reauthorize the access, the scope of access being reauthorized, and what added value your app provides when the access is reauthorized.
_facebookSignIn.reauthorizeDataAccess().then((result) {
print('Reauthorize data access status ::: ${result?.status}');
print('Reauthorize data access token ::: ${result?.accessToken?.toJson()}');
});
Troubleshooting
If you haven't completed AndroidX setup in your Flutter project, your project might not build. The simple solution is adding 2 lines in your android/gradle.properties:
android.useAndroidX=true
android.enableJetifier=true
For more, see "AndroidX compatibility" in the official Flutter documentation.
Libraries
- enums/enums
- enums/facebook_login_behavior
- enums/facebook_login_status
- enums/ios_login_tracking_type
- enums/login_type
- extensions/enum_extensions
- extensions/extensions
- extensions/string_extensions
- lecle_flutter_facebook_login
- models/facebook_access_token
- models/facebook_login_result
- models/facebook_picture_data
- models/facebook_user_profile
- models/login_configuration
- models/models