X

Flutter Facebook Login Integration in Your App

 

Flutter Facebook Authentication :

Flutter facebook authentication integration is used to make a simple and safe login to your app to maintain the security, instead of creating multiple credentials for different apps.

When you create a app you sometimes need to provide security restrictions i.e., implement user login and based on login provide services to the user.

Not only security login also allows you to locate user individually and know their usage and can provide better services based on their usages.

When you implement any new offer based on the user’s database you can process them and avoid invalid usages of the services.

You need not maintain a database for user logins you can make use of different third party logins to you app like Google, facebook, twitter, linked in and more.

Facebook login provides user details like name, email address, phone number, profile picture if required providing enough privacy to safeguard user details.

User can know the apps he logged-in using facebook and can remove the apps if not required anymore through facebook app settings console.

 

Flutter facebook authentication video tutorial :

Go through the below tutorial for more details on implementation on flutter facebook authentication.

 

Project Structure :

This below image depicts the project structure of flutter facebook login.

pubspec.yaml :

Add a flutter facebook login dependency adjust the versions according to the latest available.

dependencies:
  flutter:
    sdk: flutter
  flutter_facebook_login: ^3.0.0

 

 

strings.xml :

Provide the common Strings to be used in the app

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">Login</string>
    <string name="facebook_app_id">1**************</string>
    <string name="fb_login_protocol_scheme">fb1************</string>
</resources>

 

 

AndroidManifest.xml :

Specify meta data and facebook activity in android manifest file.

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

 


 

Info.plist :

Specify the facebook id for iOS app inside Info plist file.

<key>FacebookAppID</key>
<!-- Replace "YOUR_FACEBOOK_APP_ID" with your Facebook App ID here. -->
<string>YOUR_FACEBOOK_APP_ID</string>

<key>FacebookDisplayName</key>
<!-- Replace "Your App Name" with your Facebook App name. -->
<string>Your App Name</string>

<key>LSApplicationQueriesSchemes</key>
<array>
    <string>fbapi</string>
    <string>fb-messenger-share-api</string>
    <string>fbauth2</string>
    <string>fbshareextension</string>
</array>

 

 


main.dart :

Initialize with void main() consider the default class MyApp()

void main() => runApp(new MyApp());

 

 

Declare a facebookSignIn object

static final FacebookLogin facebookSignIn = new FacebookLogin();

 

 

Add a sample design to make a user login with two buttons and display the login details after log-in.

Column(
  mainAxisAlignment: MainAxisAlignment.center,
  children: <Widget>[
    Text(_message),
    RaisedButton(
      onPressed: _login,
      child: Text('Log in'),
    ),
    RaisedButton(
      onPressed: _logOut,
      child: Text('Logout'),
    ),
  ],
),

 

 

Facebook login async method

Future<void> _login() async {
  final FacebookLoginResult result = await facebookSignIn.logIn(['email']);
  
  switch (result.status) {
    case FacebookLoginStatus.loggedIn:
      final FacebookAccessToken accessToken = result.accessToken;
      _showMessage('''
       Logged in!
       
       Token: ${accessToken.token}
       User id: ${accessToken.userId}
       Expires: ${accessToken.expires}
       Permissions: ${accessToken.permissions}
       Declined permissions: ${accessToken.declinedPermissions}
       ''');
      break;
    case FacebookLoginStatus.cancelledByUser:
      _showMessage('Login cancelled by the user.');
      break;
    case FacebookLoginStatus.error:
      _showMessage('Something went wrong with the login process.\n'
          'Here\'s the error Facebook gave us: ${result.errorMessage}');
      break;
  }
}

 

 

logout async method

Future<void> _logOut() async {
  await facebookSignIn.logOut();
  _showMessage('Logged out.');
}

 

 

declare a method to display a message

void _showMessage(String message) {
  setState(() {
    _message = message;
  });
}

 

 

Full Code :

Offering complete code for integrating Facebook login in Flutter.


import 'dart:async';

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

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  static final FacebookLogin facebookSignIn = FacebookLogin();

  String _message = 'Log in/out by pressing the buttons below.';

  Future<void> _login() async {
    final FacebookLoginResult result =
        await facebookSignIn.logIn(['email']);

    switch (result.status) {
      case FacebookLoginStatus.loggedIn:
        final FacebookAccessToken accessToken = result.accessToken;
        _showMessage('''
         Logged in!
         
         Token: ${accessToken.token}
         User id: ${accessToken.userId}
         Expires: ${accessToken.expires}
         Permissions: ${accessToken.permissions}
         Declined permissions: ${accessToken.declinedPermissions}
         ''');
        break;
      case FacebookLoginStatus.cancelledByUser:
        _showMessage('Login cancelled by the user.');
        break;
      case FacebookLoginStatus.error:
        _showMessage('Something went wrong with the login process.\n'
            'Here\'s the error Facebook gave us: ${result.errorMessage}');
        break;
    }
  }

  Future<void> _logOut() async {
    await facebookSignIn.logOut();
    _showMessage('Logged out.');
  }

  void _showMessage(String message) {
    setState(() {
      _message = message;
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Facebook Login'),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Text(_message),
              RaisedButton(
                onPressed: _login,
                child: Text('Log in'),
              ),
              RaisedButton(
                onPressed: _logOut,
                child: Text('Logout'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

 

Flutter Facebook Authentication output :

The following screen demonstrates how to utilize Flutter Facebook login feature.

If you have any questions, feel free to drop them in the comments below. If you enjoyed this tutorial, show us some love by liking and sharing for more exciting updates

abhishek:
Related Post

This website uses cookies.