Checkout MyThemeBox.com for Ionic & Flutter Themes

Flutter Facebook login with Example

flutter-facebook-login-example

Hey Everyone! This article, I'm going to explain how to integrate facebook login with Flutter. To do that, we need to use the flutterfacebooklogin package (Link: https://pub.dev/packages/flutterfacebooklogin )

What you'll learn?

  • Implementing Facebook Login with your flutter app
  • Accessing User Profile such as name, profile picture, email using graph API
  • logout

Flutter Facebook Login Steps

  • Creating Facebook Application & get APP name & App ID
  • Adding Facebook Package
  • Create a strings.xml file in your android folder
  • Configure your AndroidManifest.xml file
  • Implementing Facebook login functionalities with your flutter app

Step 1: Create a Facebook App ID & App Name

To create facebook App Id & App name, you can follow this my existing article here (https://codesundar.com/create-facebook-application/). As a result, you must get an App ID & APP name.

Important things to note:

  • you must update your Android package name in **android/app/build.gradle** file (defaultConfig)

Step 2: Adding Facebook Package

Open your pubspec.yaml file & declare flutterfacebooklogin package & HTTP package in your dependencies

dependencies:
  flutter:
    sdk: flutter
  http: ^0.12.0+2
  flutter_facebook_login: ^1.2.0

where HTTP used to work with Facebook Graph API request. Please add a flutterfacebooklogin latest version in order to work with AndroidX Support

Step 3: Configuring your Android App

In order to work with Facebook login, we must configure our android app. To do that, we need to create a file name called **strings.xml** in **android/app/src/main/res/values/strings.xml**

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">CodeSundar</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>
</resources>

Note: Please update app id, app name, protocol_scheme with your own credentials

Once you created the **strings.xml** file, you need to copy paste this to **AndroidManifest.xml** (between )

<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>

So final code looks like

<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.auth">

    <!-- io.flutter.app.FlutterApplication is an android.app.Application that
          calls FlutterMain.startInitialization(this); in its onCreate method.
          In most cases you can leave this as-is, but you if you want to provide
          additional functionality it is fine to subclass or reimplement
          FlutterApplication and put your custom class here. -->
    <application android:name="io.flutter.app.FlutterApplication" android:label="auth" android:icon="@mipmap/ic_launcher">
        <activity android:name=".MainActivity" android:launchMode="singleTop" android:theme="@style/LaunchTheme" android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode" android:hardwareAccelerated="true" android:windowSoftInputMode="adjustResize">
            <!-- This keeps the window background of the activity showing
                  until Flutter renders its first frame. It can be removed if
                  there is no splash screen (such as the default splash screen
                  defined in @style/LaunchTheme). -->
            <meta-data android:name="io.flutter.app.android.SplashScreenUntilFirstFrame" android:value="true" />
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>

        <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>
    </application>
</manifest>

Step 4: Implementing Facebook login in Flutter App

Copy & paste this code to main.dart . I have explained the code below

import 'package:flutter/material.dart';
import 'package:flutter_facebook_login/flutter_facebook_login.dart';
import 'package:http/http.dart' as http;
import 'dart:convert' as JSON;

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _MyAppState();
  }
}

class _MyAppState extends State<MyApp> {
  bool _isLoggedIn = false;
  Map userProfile;
  final facebookLogin = FacebookLogin();

  _loginWithFB() async{

    
    final result = await facebookLogin.logInWithReadPermissions(['email']);

    switch (result.status) {
      case FacebookLoginStatus.loggedIn:
        final token = result.accessToken.token;
        final graphResponse = await http.get('https://graph.facebook.com/v2.12/me?fields=name,picture,email&access_token=${token}');
        final profile = JSON.jsonDecode(graphResponse.body);
        print(profile);
        setState(() {
          userProfile = profile;
          _isLoggedIn = true;
        });
        break;

      case FacebookLoginStatus.cancelledByUser:
        setState(() => _isLoggedIn = false );
        break;
      case FacebookLoginStatus.error:
        setState(() => _isLoggedIn = false );
        break;
    }

  }

  _logout(){
    facebookLogin.logOut();
    setState(() {
      _isLoggedIn = false;
    });
  }

  
  Widget build(BuildContext context) {
    // TODO: implement build
    return MaterialApp(
      home: Scaffold(
        body: Center(
            child: _isLoggedIn
                ? Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      Image.network(userProfile["picture"]["data"]["url"], height: 50.0, width: 50.0,),
                      Text(userProfile["name"]),
                      OutlineButton( child: Text("Logout"), onPressed: (){
                        _logout();
                      },)
                    ],
                  )
                : Center(
                    child: OutlineButton(
                      child: Text("Login with Facebook"),
                      onPressed: () {
                        _loginWithFB();
                      },
                    ),
                  )),
      ),
    );
  }
}

Code Explanation:

  • First, we imported the required packages. In our case, we need to import flutterfacebooklogin (for working with Facebook login), HTTP (for accessing Graph API from facebook), dart:convert (for decoding JSON)
  • We have used StateFulWidget because we need to work with the state such as isLoggedIn, userProfile
  • Inside Scaffold body, we created Center Widget & Inside Center widget, we created a ternary operator for isLoggedIn
  • If the user is authenticated, we need to display profile information such as profile picture, full name with a logout button
  • Else, we have to display the login button.
  • When the user presses the login button, we need to authenticate the user. If failed with error (or) canceled by the user, we setting isLoggedIn as false
  • If success, we'll receive an access token. Using the access token we can request a picture, name, first_name, email via facebook graph api

Hope you enjoy this flutter facebook login tutorial. If you faced any issue, feel free to comment below.