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: http://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

<span class="hljs-symbol">dependencies:</span>
<span class="hljs-symbol">  flutter:</span>
<span class="hljs-symbol">    sdk:</span> flutter
<span class="token key atrule">  flutter_facebook_auth</span><span class="token punctuation">:</span> ^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

<span class="php"><span class="hljs-meta"><?</span>xml version=<span class="hljs-string">"1.0"</span> encoding=<span class="hljs-string">"utf-8"</span><span class="hljs-meta">?></span></span>
<span class="hljs-tag"><<span class="hljs-name">resources</span>></span>
    <span class="hljs-tag"><<span class="hljs-name">string</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"app_name"</span>>c</span>odeSundar<span class="hljs-tag"></<span class="hljs-name">string</span>></span>
    <span class="hljs-tag"><<span class="hljs-name">string</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"facebook_app_id"</span>></span>000000000000<span class="hljs-tag"></<span class="hljs-name">string</span>></span>
    <span class="hljs-tag"><<span class="hljs-name">string</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"fb_login_protocol_scheme"</span>></span>fb000000000000<span class="hljs-tag"></<span class="hljs-name">string</span>></span>
<span class="hljs-tag"></<span class="hljs-name">resources</span>></span>

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 )

<span class="hljs-tag"><<span class="hljs-name">meta-data</span> <span class="hljs-attr">android:name</span>=<span class="hljs-string">"com.facebook.sdk.ApplicationId"</span> <span class="hljs-attr">android:value</span>=<span class="hljs-string">"@string/facebook_app_id"</span>/></span>
<span class="hljs-tag"><<span class="hljs-name">activity</span> <span class="hljs-attr">android:name</span>=<span class="hljs-string">"com.facebook.FacebookActivity"</span> <span class="hljs-attr">android:configChanges</span>=
    <span class="hljs-string">"keyboard|keyboardHidden|screenLayout|screenSize|orientation"</span> <span class="hljs-attr">android:label</span>=<span class="hljs-string">"@string/app_name"</span> /></span>

<span class="hljs-tag"><<span class="hljs-name">activity</span> <span class="hljs-attr">android:name</span>=<span class="hljs-string">"com.facebook.CustomTabActivity"</span> <span class="hljs-attr">android:exported</span>=<span class="hljs-string">"true"</span>></span>
    <span class="hljs-tag"><<span class="hljs-name">intent-filter</span>></span>
        <span class="hljs-tag"><<span class="hljs-name">action</span> <span class="hljs-attr">android:name</span>=<span class="hljs-string">"android.intent.action.VIEW"</span> /></span>
        <span class="hljs-tag"><<span class="hljs-name">category</span> <span class="hljs-attr">android:name</span>=<span class="hljs-string">"android.intent.category.DEFAULT"</span> /></span>
        <span class="hljs-tag"><<span class="hljs-name">category</span> <span class="hljs-attr">android:name</span>=<span class="hljs-string">"android.intent.category.BROWSABLE"</span> /></span>
        <span class="hljs-tag"><<span class="hljs-name">data</span> <span class="hljs-attr">android:scheme</span>=<span class="hljs-string">"@string/fb_login_protocol_scheme"</span> /></span>
    <span class="hljs-tag"></<span class="hljs-name">intent-filter</span>></span>
<span class="hljs-tag"></<span class="hljs-name">activity</span>></span>

So final code looks like

<span class="hljs-tag"><<span class="hljs-name">manifest</span> <span class="hljs-attr">xmlns:android</span>=<span class="hljs-string">"http://schemas.android.com/apk/res/android"</span> <span class="hljs-attr">package</span>=<span class="hljs-string">"com.example.auth"</span>></span>

    <span class="hljs-comment"><!-- 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. --></span>
    <span class="hljs-tag"><<span class="hljs-name">application</span> <span class="hljs-attr">android:name</span>=<span class="hljs-string">"io.flutter.app.FlutterApplication"</span> <span class="hljs-attr">android:label</span>=<span class="hljs-string">"auth"</span> <span class="hljs-attr">android:icon</span>=<span class="hljs-string">"@mipmap/ic_launcher"</span>></span>
        <span class="hljs-tag"><<span class="hljs-name">activity</span> <span class="hljs-attr">android:name</span>=<span class="hljs-string">".MainActivity"</span> <span class="hljs-attr">android:launchMode</span>=<span class="hljs-string">"singleTop"</span> <span class="hljs-attr">android:theme</span>=<span class="hljs-string">"@style/LaunchTheme"</span> <span class="hljs-attr">android:configChanges</span>=<span class="hljs-string">"orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"</span> <span class="hljs-attr">android:hardwareAccelerated</span>=<span class="hljs-string">"true"</span> <span class="hljs-attr">android:windowSoftInputMode</span>=<span class="hljs-string">"adjustResize"</span>></span>
            <span class="hljs-comment"><!-- 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). --></span>
            <span class="hljs-tag"><<span class="hljs-name">meta-data</span> <span class="hljs-attr">android:name</span>=<span class="hljs-string">"io.flutter.app.android.SplashScreenUntilFirstFrame"</span> <span class="hljs-attr">android:value</span>=<span class="hljs-string">"true"</span> /></span>
            <span class="hljs-tag"><<span class="hljs-name">intent-filter</span>></span>
                <span class="hljs-tag"><<span class="hljs-name">action</span> <span class="hljs-attr">android:name</span>=<span class="hljs-string">"android.intent.action.MAIN"</span>/></span>
                <span class="hljs-tag"><<span class="hljs-name">category</span> <span class="hljs-attr">android:name</span>=<span class="hljs-string">"android.intent.category.LAUNCHER"</span>/></span>
            <span class="hljs-tag"></<span class="hljs-name">intent-filter</span>></span>
        <span class="hljs-tag"></<span class="hljs-name">activity</span>></span>

        <span class="hljs-tag"><<span class="hljs-name">meta-data</span> <span class="hljs-attr">android:name</span>=<span class="hljs-string">"com.facebook.sdk.ApplicationId"</span> <span class="hljs-attr">android:value</span>=<span class="hljs-string">"@string/facebook_app_id"</span>/></span>

        <span class="hljs-tag"><<span class="hljs-name">activity</span> <span class="hljs-attr">android:name</span>=<span class="hljs-string">"com.facebook.FacebookActivity"</span> <span class="hljs-attr">android:configChanges</span>=
            <span class="hljs-string">"keyboard|keyboardHidden|screenLayout|screenSize|orientation"</span> <span class="hljs-attr">android:label</span>=<span class="hljs-string">"@string/app_name"</span> /></span>

        <span class="hljs-tag"><<span class="hljs-name">activity</span> <span class="hljs-attr">android:name</span>=<span class="hljs-string">"com.facebook.CustomTabActivity"</span> <span class="hljs-attr">android:exported</span>=<span class="hljs-string">"true"</span>></span>
            <span class="hljs-tag"><<span class="hljs-name">intent-filter</span>></span>
                <span class="hljs-tag"><<span class="hljs-name">action</span> <span class="hljs-attr">android:name</span>=<span class="hljs-string">"android.intent.action.VIEW"</span> /></span>
                <span class="hljs-tag"><<span class="hljs-name">category</span> <span class="hljs-attr">android:name</span>=<span class="hljs-string">"android.intent.category.DEFAULT"</span> /></span>
                <span class="hljs-tag"><<span class="hljs-name">category</span> <span class="hljs-attr">android:name</span>=<span class="hljs-string">"android.intent.category.BROWSABLE"</span> /></span>
                <span class="hljs-tag"><<span class="hljs-name">data</span> <span class="hljs-attr">android:scheme</span>=<span class="hljs-string">"@string/fb_login_protocol_scheme"</span> /></span>
            <span class="hljs-tag"></<span class="hljs-name">intent-filter</span>></span>
        <span class="hljs-tag"></<span class="hljs-name">activity</span>></span>
    <span class="hljs-tag"></<span class="hljs-name">application</span>></span>
<span class="hljs-tag"></<span class="hljs-name">manifest</span>></span>

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.