Flutter Facebook Login - A Complete Guide to Facebook login with Flutter

Flutter Facebook Login - A Complete Guide to Facebook login with Flutter

In this post we are going to learn howto integrate facebook login with flutter application

We need to follow below steps

  • Working with Facebook apps
  • Working with Andorid Configuration
  • Working wiht Dart code

In this post we are going to use flutter_facebook_login flugin

What you will learn?

Let's Start

Create new flutter application

pubspec.yaml

Add flutter_facebook_login flugin

dev_dependencies:
  flutter_test:
    sdk: flutter
  flutter_facebook_login: ^3.0.0

 

Working with dart code

Now we need to work with Dart code. First import required packages
Here we are going to use below packages

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

 

Now we need to create Facebook Login and Logout functionality

var _isLoggedIn=false;
  Map userData;
  final facebookLogin = FacebookLogin();
  _loginWithFB() async{

    final result = await facebookLogin.logIn(['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);
        setState(() {
          userData = profile;
          _isLoggedIn = true;
        });
        break;

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

  }

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

 

Here we are managing the Login state with   _isLoggedIn varibale
We are managagint the FB login with FacebookLogin() instance

Now it's time to create Facebook App

Goto developers.facebook.com and create new application

Select Create App and enter your App name

Now select Facebook Login and select Android 

Enter your project details

Enter Package Name and Main Activity and click Save and Continue

 

Now its time t create Hash key to your application

Just put below code in MainActivity and check your log and copy and past that keyhash value

try {
            val info = packageManager.getPackageInfo(
                    "rrtutors.flutter_fb_login",
                    PackageManager.GET_SIGNATURES)
            for (signature in info.signatures) {
                val md = MessageDigest.getInstance("SHA")
                md.update(signature.toByteArray())
                Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT))
            }
        } catch (e: NameNotFoundException) {

        } catch (e: NoSuchAlgorithmException) {

        }

and past in KeyHash filed 

Now add below code in your manifest file

<!-- Facebook Login configuration -->
        <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" 
            android:exported="true"
            />
        <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>    

Here facebook_app_id is you facebook app id

Complete Code

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

class FBLogin extends StatefulWidget{
  @override
  State<StatefulWidget> createState() {
   return FBLoginState();
  }

}

class FBLoginState extends State<FBLogin> {
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text("Facebook Login"),backgroundColor: Colors.pink,),
        body: Center(
          child: _isLoggedIn
          ? Column(
           mainAxisAlignment: MainAxisAlignment.center,
           children: <Widget>[
             Image.network(userData["picture"]["data"]["url"], height: 50.0, width: 50.0,),
             Text(userData["name"]),
             RaisedButton(
               color: Colors.pink, child: Text("Logout",style: TextStyle(color: Colors.white),), onPressed: (){
               _logout();
             },)
           ],
          )
               : Center(
      child: RaisedButton(
        color: Colors.pink,
      child: Text("Login with Facebook",style: TextStyle(color: Colors.white),),
      onPressed: () {
          _loginWithFB();
      },
    ),
    ),
        ),
      ),
    );
  }
  var _isLoggedIn=false;
  Map userData;
  final facebookLogin = FacebookLogin();
  _loginWithFB() async{

    final result = await facebookLogin.logIn(['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);
        setState(() {
          userData = profile;
          _isLoggedIn = true;
        });
        break;

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

  }

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

 

Now let's run the app and check the result