flutter_login_facebook 0.2.0+1

  • Readme
  • Changelog
  • Example
  • Installing
  • 93

flutter_login_facebook #

pub package

Flutter Plugin to login via Facebook.

Easily add Facebook login feature in your application. User profile information included.

SDK version #

Facebook SDK version, used in plugin:

Minimum requirements #

  • iOS 9.0 and higher.
  • Android 4.1 and newer (SDK 16).

Getting Started #

To use this plugin:

  1. add flutter_login_facebook as a dependency in your pubspec.yaml file;
  2. setup android;
  3. setup ios;
  4. additional Facebook app setup;
  5. use plugin in application.

See Facebook Login documentation for full information.

Also you can read the article on Medium with detailed instructions.

Android #

Go to Facebook Login for Android - Quickstart page.

Select an App or Create a New App

You need to complete Step 1: Select an App or Create a New App.

Skip Step 2 (Download the Facebook App) and Step 3 (Integrate the Facebook SDK).

Edit Your Resources and Manifest

Complete Step 4: Edit Your Resources and Manifest

  • Add values to /android/app/src/main/res/values/strings.xml (create file if it doesn't exist)
  • Add a meta-data element and activities to android/app/src/main/AndroidManifest.xml, section application:
    <meta-data android:name="com.facebook.sdk.ApplicationId" 
        android:value="@string/facebook_app_id"/>
    
    <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>

See full AndroidManifest.xml in example.

Setup Facebook App

Complete Step 5: Associate Your Package Name and Default Class with Your App.

  1. Set Package Name - your package name for Android application (attribute package in AndroidManifest.xml).
  2. Set Default Activity Class Name - your main activity class (with package). By default it would be com.yourcompany.yourapp.MainActivity.
  3. Click "Save".

Complete Step 6: Provide the Development and Release Key Hashes for Your App.

  1. Generate Development and Release keys as described in the documentation. Note: if your application uses Google Play App Signing than you should get certificate SHA-1 fingerprint from Google Play Console and convert it to base64
echo "{sha1key}" | xxd -r -p | openssl base64
  1. Add generated keys in Key Hashes.
  2. Click "Save".

⚠️ Important! You should add key hashes for every build variants. E.g. if you have CI/CD which build APK for testing with it's own cerificate (it may be auto generated debug cetificate or some another) than you should add it's key too.

In the next Step 7 Enable Single Sign On for Your App you can enable Single Sing On if you want to.

And that's it for Android.

iOS #

Go to Facebook Login for iOS - Quickstart.

Select an App or Create a New App

You need to complete Step 1: Select an App or Create a New App. If you've created an app during an Android setup than use it.

Skip Step 2 (Set up Your Development Environment) and Step 3 (Integrate the Facebook SDK).

Register and Configure Your App with Facebook

Complete Step 3: Register and Configure Your App with Facebook.

  1. Add your Bundle Identifier - set Bundle ID (you can find it in Xcode: Runner - Target Runner - General, section Identity, field Bundle Identifier) and click "Save".
  2. Enable Single Sign-On for Your App if you need it and click "Save".

Configure Your Project

Complete Step 4: Configure Your Project.

Configure Info.plist (ios/Runner/Info.plist):

  1. In Xcode right-click on Info.plist, and choose Open As Source Code.
  2. Copy and paste the following XML snippet into the body of your file (<dict>...</dict>), replacing [APP_ID] with Facebook application id and [APP_NAME] with Facebook application name (you can copy prepared values from Step 4 in Facebook Quickstart).
<key>CFBundleURLTypes</key>
<array>
  <dict>
  <key>CFBundleURLSchemes</key>
  <array>
    <string>fb[APP_ID]</string>
  </array>
  </dict>
</array>
<key>FacebookAppID</key>
<string>[APP_ID]</string>
<key>FacebookDisplayName</key>
<string>[APP_NAME]</string>
  1. Also add to Info.plist body (<dict>...</dict>):
<key>LSApplicationQueriesSchemes</key>
<array>
  <string>fbapi</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>
  <string>fbauth</string>
  <string>fb-messenger-share-api</string>
  <string>fbauth2</string>
  <string>fbshareextension</string>
</array>

See full Info.plist in example.

⚠️ NOTE. Check if you already have CFBundleURLTypes or LSApplicationQueriesSchemes keys in your Info.plist. If you have, you should merge their values, instead of adding a duplicate key.

Skip Step 5 (Connect Your App Delegate) and all the rest.

And that's it for iOS.

Additional Facebook app setup #

Go to My App on Facebook and select your application.

Icon

You should add the App Icon (in Settings -> Basic) to let users see your application icon instead of the default icon when they attempt to log in.

Add store IDs

In Setting -> Basic -> iOS fill up field "iPhone Store ID" ("iPad Store ID").

Optional settings

You may want to change some other settings. For example Display Name, Contact Email, Category, etc.

Enable application

By default, your application has the status "In development".

You should enable application before log in feature goes public.

Facebook will show a warning if your application is not fully set up. For example, you may need to provide a Privacy Policy. You can use your Privacy Policy from Google Play/App Store.

Usage in application #

You can:

  • log in via Facebook;
  • get access token;
  • get user profile;
  • get user profile image url;
  • get user email (if has permissions);
  • check if logged in;
  • log out.

Sample code:

import 'package:flutter_login_facebook/flutter_login_facebook.dart';

// Create an instance of FacebookLogin
final fb = FacebookLogin();

// Log in
final res = await fb.logIn(permissions: [
  FacebookPermission.publicProfile,
  FacebookPermission.email,
]);

// Check result status
switch (res.status) {
  case FacebookLoginStatus.Success:
    // Logged in
    
    // Send this access token to server for validation and auth
    final accessToken = res.accessToken;
    // Send access token to server for validation and auth
    final FacebookAccessToken accessToken = res.accessToken;
    print('Access token: ${accessToken.token}');

    // Get profile data
    final profile = await fb.getUserProfile();
    print('Hello, ${profile.name}! You ID: ${profile.userId}');

    // Get user profile image url
    final imageUrl = await plugin.getProfileImageUrl(width: 100);
    print('Your profile image: $imageUrl');

    // Get email (since we request email permission)
    final email = await fb.getUserEmail();
    // But user can decline permission
    if (email != null)
      print('And your email is $email');

    break;
  case FacebookLoginStatus.Cancel:
    // User cancel log in
    break;
  case FacebookLoginStatus.Error:
    // Log in failed
    print('Error while log in: ${res.error}');
    break;
}

Next release #

0.2.0+1 - 2020-06-21 #

  • Readme: add information about usage getProfileImageUrl().

0.2.0 - 2020-06-20 #

  • Method to get user profile image.

0.1.2+4 - 2020-06-20 #

0.1.2+3 - 2020-06-11 #

  • Fixed: intercept all open urls and launches, even though it can't be handled.
  • Minor readme improvements.

0.1.2+2 - 2020-06-03 #

  • Readme: fix links urls.
  • Readme: fix some errors in text.
  • Readme: Medium article link.

0.1.2+1 - 2020-05-27 #

  • Readme: add log in error handling.
  • Fixed mistake in Readme.

0.1.2 - 2020-05-27 #

  • An ability to get user email (if have permissions).
  • Add declinedPermissions in AccessToken.

0.1.1+1 - 2020-05-22 #

  • [android] Fixed: reset activity is never called.

0.1.1 - 2020-05-22 #

  • Add error information for login failure.
  • Readme: add information about additional key hashes.
  • Mute exception furing get profile.

0.1.0+1 - 2020-05-19 #

  • More detailed description.

0.1.0 - 2020-05-19 #

  • Core functionality (iOS/Android).

example/lib/main.dart

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_login_facebook/flutter_login_facebook.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  final plugin = FacebookLogin(debug: true);

  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _sdkVersion;
  FacebookAccessToken _token;
  FacebookUserProfile _profile;
  String _email;
  String _imageUrl;

  @override
  void initState() {
    super.initState();

    _getSdkVersion();
    _updateLoginInfo();
  }

  @override
  Widget build(BuildContext context) {
    final isLogin = _token != null && _profile != null;
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Login via Facebook example'),
        ),
        body: Padding(
          padding: const EdgeInsets.symmetric(vertical: 18.0, horizontal: 8.0),
          child: Center(
            child: Column(
              children: <Widget>[
                if (_sdkVersion != null) Text("SDK v$_sdkVersion"),
                if (isLogin)
                  Padding(
                    padding: const EdgeInsets.only(bottom: 10),
                    child: _buildUserInfo(context, _profile, _token, _email),
                  ),
                isLogin
                    ? OutlineButton(
                        child: Text('Log Out'),
                        onPressed: _onPressedLogOutButton,
                      )
                    : OutlineButton(
                        child: Text('Log In'),
                        onPressed: _onPressedLogInButton,
                      ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildUserInfo(BuildContext context, FacebookUserProfile profile,
      FacebookAccessToken accessToken, String email) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        if (_imageUrl != null)
          Center(
            child: Image.network(_imageUrl),
          ),
        Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            Text('User: '),
            Text(
              '${profile.firstName} ${profile.lastName}',
              style: const TextStyle(fontWeight: FontWeight.bold),
            ),
          ],
        ),
        Text('AccessToken: '),
        Container(
          child: Text(
            accessToken.token,
            softWrap: true,
          ),
        ),
        if (email != null) Text('Email: $email'),
      ],
    );
  }

  void _onPressedLogInButton() async {
    await widget.plugin.logIn(permissions: [
      FacebookPermission.publicProfile,
      FacebookPermission.email,
    ]);
    _updateLoginInfo();
  }

  void _onPressedLogOutButton() async {
    await widget.plugin.logOut();
    _updateLoginInfo();
  }

  void _getSdkVersion() async {
    final sdkVesion = await widget.plugin.sdkVersion;
    setState(() {
      _sdkVersion = sdkVesion;
    });
  }

  void _updateLoginInfo() async {
    final plugin = widget.plugin;
    final token = await plugin.accessToken;
    FacebookUserProfile profile;
    String email;
    String imageUrl;

    if (token != null) {
      profile = await plugin.getUserProfile();
      if (token.permissions?.contains(FacebookPermission.email.name) ?? false)
        email = await plugin.getUserEmail();
      imageUrl = await plugin.getProfileImageUrl(width: 100);
    }

    setState(() {
      _token = token;
      _profile = profile;
      _email = email;
      _imageUrl = imageUrl;
    });
  }
}

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  flutter_login_facebook: ^0.2.0+1

2. Install it

You can install packages from the command line:

with Flutter:


$ flutter pub get

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:flutter_login_facebook/flutter_login_facebook.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
86
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
100
Overall:
Weighted score of the above. [more]
93
Learn more about scoring.

We analyzed this package on Jul 11, 2020, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.8.4
  • pana: 0.13.15
  • Flutter: 1.17.5

Analysis suggestions

Package does not support Flutter platform Linux

Because:

  • package:flutter_login_facebook/flutter_login_facebook.dart that declares support for platforms: Android, iOS

Package does not support Flutter platform Web

Because:

  • package:flutter_login_facebook/flutter_login_facebook.dart that declares support for platforms: Android, iOS

Package does not support Flutter platform Windows

Because:

  • package:flutter_login_facebook/flutter_login_facebook.dart that declares support for platforms: Android, iOS

Package does not support Flutter platform macOS

Because:

  • package:flutter_login_facebook/flutter_login_facebook.dart that declares support for platforms: Android, iOS

Package not compatible with SDK dart

Because:

  • flutter_login_facebook that is a package requiring null.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.7.0 <3.0.0
flutter 0.0.0
list_ext ^0.1.6 0.1.10
Transitive dependencies
collection 1.14.12 1.14.13
matcher 0.12.8
meta 1.1.8 1.2.2
path 1.7.0
quiver 2.1.3
sky_engine 0.0.99
stack_trace 1.9.5
typed_data 1.1.6 1.2.0
vector_math 2.0.8 2.1.0-nullsafety
Dev dependencies
flutter_test