Flutter Facebook Login

flutter-facebook-login-tutorial
flutter-facebook-login-tutorial

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

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

dependencies:
  flutter:
    sdk: flutter
  flutter_facebook_auth: ^3.3.2

where HTTP used to work with Facebook Graph API request. Please add a flutter_facebook_login 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>
    <string name="facebook_app_id">000000000000</string>
    <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

import 'package:flutter/material.dart';
import 'package:flutter_facebook_auth/flutter_facebook_auth.dart';

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  bool _isLoggedIn = false;
  Map _userObj = {};

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Codesundar"),
      ),
      body: Container(
        child: _isLoggedIn
            ? Column(
                children: [
                  Image.network(_userObj["picture"]["data"]["url"]),
                  Text(_userObj["name"]),
                  Text(_userObj["email"]),
                  TextButton(
                      onPressed: () {
                        FacebookAuth.instance.logOut().then((value) {
                          setState(() {
                            _isLoggedIn = false;
                            _userObj = {};
                          });
                        });
                      },
                      child: Text("Logout"))
                ],
              )
            : Center(
                child: ElevatedButton(
                  child: Text("Login with Facebook"),
                  onPressed: () async {
                    FacebookAuth.instance.login(
                        permissions: ["public_profile", "email"]).then((value) {
                      FacebookAuth.instance.getUserData().then((userData) {
                        setState(() {
                          _isLoggedIn = true;
                          _userObj = userData;
                        });
                      });
                    });
                  },
                ),
              ),
      ),
    );
  }
}

Code Explanation:

    • First, we imported the required packages. In our case, we need to import flutter_facebook_auth (for working with Facebook login)
    • 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

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