Newby Coder header banner

Flutter Facebook Login

flutter_facebook_login package (https://pub.dev/packages/flutter_facebook_login) is used to integrate facebook login with Flutter

It provides FacebookLogin().logIn() method which redirects a user to login to Facebook via webview of default browser and grant permission to application to access profile information

Usage

Import

Import flutter_facebook_login module for facebook login and flutter_auth_buttons for FacebookSignInButton

import 'package:flutter_auth_buttons/flutter_auth_buttons.dart';
import 'package:flutter_facebook_login/flutter_facebook_login.dart';
Initiate webview login workflow

logIn function takes an array of entities representing private data like 'email' for which permission is to be requested

final facebookLogin = FacebookLogin();
final token = await facebookLogin.logIn(['email']).accessToken.token;
Retrieve profile data using graph api

Use access token returned by logIn() after a valid login to send graph api request

final graphResponse = await http.get('https://graph.facebook.com/v2.12/me?fields=name,picture,email&access_token=${token}');
// decode http response body
final profile = json.decode(graphResponse.body);

It contains a user id which can be used to create a user account in Firebase for the application or can be sent to a private server with custom implementation of user accounts

Log out
await facebookLogin.logOut()

Creating new Flutter App

Check Flutter installation to setup Flutter

Use flutter create command to create a Flutter project (here named nc_fb_login) :

flutter create nc_fb_login

Prerequisite

Create a Facebook App ID & App Name

Login to https://developers.facebook.com/ and click on MyApps

Click on Create a new app

cl-facebook-create-app

Select an option which mentions Facebook Login (option 3)

cl-facebook-create-app-select-type

Enter app id which should not contain Facebook trademark or brand elements like fb, and click Create App ID

cl-facebook-create-app-enter-appid

Android settings


Dependency

Flutter App Code

device_location_app/pubspec.yaml
import 'package:flutter/material.dart';
// for json.decode()
import 'dart:convert';
// for async keyword
import 'dart:async';
// to send facebook graph api request
import 'package:http/http.dart' as http;
// for FacebookSignInButton
import 'package:flutter_auth_buttons/flutter_auth_buttons.dart';
// to initiate Facebook webview login
import 'package:flutter_facebook_login/flutter_facebook_login.dart';


void main() => runApp(new MaterialApp(
  title: 'Flutter Authentication App',
  home: new LoginPage(),
));

class LoginPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => new _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  final GlobalKey<FormState> _formKey = new GlobalKey<FormState>();
  final facebookLogin = FacebookLogin();
  // state variable to store profile data
  var _fbUser;

  // onPressed handler for FacebookSignInButton
  Future<dynamic> _handleSignIn() async {
    // facebookLogin.logIn() redirects user to login webview of Facebook (using default browser)
    final result = await facebookLogin.logIn(['email']);
    // get token from response (assuming user doesn't cancel login workflow)
    final token = result.accessToken.token;
    // send facebook graph api request to get name, picture and email
    final graphResponse = await http.get(
                'https://graph.facebook.com/v2.12/me?fields=name,picture,email&access_token=${token}');
    // decode http response body
    final profile = json.decode(graphResponse.body);
    // print(profile);
    // set state with profile data
    this.setState((){_fbUser= profile;});
  }

  Widget renderButton() {
    return Center(
      child: FacebookSignInButton(
        onPressed: this._handleSignIn,
        textStyle: TextStyle(
          fontSize: 14,
          color: Colors.white,
        ),
      ),
    );
  }

  Widget renderUser() {
      return Center(
        child: Column(
          // to center vertically
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Container( height:200, width:200, child: Card( child:Image.network(_fbUser["picture"]["data"]["url"], fit: BoxFit.cover))),
            Container(
              padding: EdgeInsets.only(top:20),
              child: Column(
                children: [
                  Text('Name: ${_fbUser["name"]}'),
                  Text('Email: ${_fbUser["email"]}'),
              ],
            ),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    // render button if user data is not available, else render retrieved user profile data
    var render = _fbUser == null? renderButton() : renderUser();
    return new Scaffold(
      appBar: new AppBar(title: new Text('Facebook Login'),),
      body: new Container(
        child: render,
      ),
    );
  }
}

Run instructions

Ensure a supported device is connected or emulator is started

Go to project directory

Use flutter run command to run

flutter run

It builds and runs app on an available android/ios device


cl-flutter-android-facebook-login1cl-flutter-android-facebook-login2cl-flutter-android-facebook-login3
cl-flutter-android-facebook-login4cl-flutter-android-facebook-login5