Flutter Facebook Login

Flutter Facebook Login

    Previously we have seen how to use Google Firebase login in Flutter. Here we will see how to Flutter Facebook login.

    As usual first create a flutter app, and then isntall the plugin flutter_facebook_auth 

      cupertino_icons: ^1.0.2
      flutter_facebook_auth:

    After that, go to Facebook developer and create an app. Click the link below to do it.

    https://developers.facebook.com/

    Follow the video to create an app with Facebook developer account. 

    Android settings

    For internet permission and not using ads in the app right before <application> tag

        <uses-permission android:name="android.permission.INTERNET"/>
        <uses-permission android:name="com.google.android.gms.permission.AD_ID" tools:node="remove"/>
            <!-- add the above two line -->
       <application
            android:label="flutter_facebook_auth_project"
            android:name="${applicationName}"
            android:icon="@mipmap/ic_launcher">
          ...................................................................

    We need to add, activity tag right before </application>

    ...................................................  
              <!-- facebook configs -->
        <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>
     
        </application>

    So your complete AndroidManifest.xml file would look like this 

    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.example.facebooktest"
        xmlns:tools="http://schemas.android.com/tools"
        >
    
    
        <uses-permission android:name="android.permission.INTERNET"/>
        <uses-permission android:name="com.google.android.gms.permission.AD_ID" tools:node="remove"/>
    
        <application
            android:label="flutter_facebook_auth_project"
            android:name="${applicationName}"
            android:icon="@mipmap/ic_launcher">
            <activity
                android:name=".MainActivity"
                android:exported="true"
                android:launchMode="singleTop"
                android:theme="@style/LaunchTheme"
                android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
                android:hardwareAccelerated="true"
                android:windowSoftInputMode="adjustResize">
                <!-- Specifies an Android theme to apply to this Activity as soon as
                     the Android process has started. This theme is visible to the user
                     while the Flutter UI initializes. After that, this theme continues
                     to determine the Window background behind the Flutter UI. -->
                <meta-data
                    android:name="io.flutter.embedding.android.NormalTheme"
                    android:resource="@style/NormalTheme"
                    />
                <intent-filter>
                    <action android:name="android.intent.action.MAIN"/>
                    <category android:name="android.intent.category.LAUNCHER"/>
                </intent-filter>
            </activity>
            <!-- Don't delete the meta-data below.
                 This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
            <meta-data
                android:name="flutterEmbedding"
                android:value="2" />
    
            <!-- facebook configs -->
            <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>
    
        </application>
    </manifest>
    

    All you need to change is the package name based on your package.

    You need to create strings.xml file for android. It should be insdie app/src/main/res/values. Create a file name strings.xml and put the code below

    <?xml version="1.0" encoding="utf-8"?>
    <resources>
        <string name="app_name">Test App</string>
        <string name="facebook_app_id">1073933219918761</string>
        <string name="fb_login_protocol_scheme">fb1073933219918761</string>
    </resources>

    In the above code you need to replace the name and ID with your own name and ID.

    iOS settings

    iOS settings are relatively simple. Just make changes in the Info.plist file. Put the code below

    <key>CFBundleURLTypes</key>
    <array>
      <dict>
      <key>CFBundleURLSchemes</key>
      <array>
        <string>fb1073933219918761</string>
      </array>
      </dict>
    </array>
    <key>FacebookAppID</key>
    <string>1073933219918761</string>
    <key>FacebookClientToken</key>
    <string>CLIENT-TOKEN</string>
    <key>FacebookDisplayName</key>
    <string>Test App</string>

    Put the above code inside Info.plist right after <dict> tag. In the above code you need to replace the name and ID with your own name and ID.

    Core methods of Facebook

    There are two functions those are particularly useful for flutter facebook login. 

    FacebookAuth.instance.login

    FaecbookAuth.instance.logout

    They are just like Firebase Google login and logout method. 

    We have used a boolean _isLoggedIn to store user login status. It becomes true once we get Facebook permission to login after clicking on the ElevatedButton. 

    At the same time we save the user data in a Map _userObj. Once we log out we set the map to empty one and also set _isloggedIn to false.

    Reqeuest login

    Center(
              child: ElevatedButton(
                child: Text("Login with Facebook"),
                onPressed: () async {
                  FacebookAuth.instance.login(
                      permissions: ["public_profile", "email"]).then((value) {
                    FacebookAuth.instance.getUserData().then((userData) async {
    
                      setState(() {
                        _isLoggedIn = true;
                        _userObj = userData;
                      });
                    });
                  });
                },
              ),
            )

    Show user data

    Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
    
                Text(_userObj["name"]),
                Text(_userObj["email"]),
                TextButton(
                    onPressed: () {
                      FacebookAuth.instance.logOut().then((value) {
                        setState(() {
                          _isLoggedIn = false;
                          _userObj = {};
                        });
                      });
                    },
                    child: Text("Logout"))
              ],
            )

    The complete code

    
    import 'package:cached_network_image/cached_network_image.dart';
    import 'package:flutter/material.dart';
    import 'package:flutter_facebook_auth/flutter_facebook_auth.dart';
    
    
    void main() => runApp(MaterialApp(home: HomePage(),));
    
    
    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("DBestech"),
          ),
          body: Container(
            width: MediaQuery.of(context).size.width,
            child: _isLoggedIn
                ? Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                CachedNetworkImage(
                  height: 200,
                  width: 200,
                  fit: BoxFit.cover,
                  imageUrl:_userObj["picture"]["data"]["url"],
                  errorWidget: (context, url, error) => Icon(Icons.error_outline),
                ),
               // 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) async {
                   
                      setState(() {
                        _isLoggedIn = true;
                        _userObj = userData;
                      });
                    });
                  });
                },
              ),
            ),
          ),
        );
      }
    }

    Courses


    Recommended posts


    Recent posts