Facebook Login In Flutter

In this article, we will learn how to implement a Facebook Login using Google Firebase Authentication in Flutter based applications.

Introduction

 
Google Firebase is trending nowadays. It has around 10 sign-in methods which include email, Google, Facebook, Phone, Twitter, and Yahoo login etc. We have covered Email/Password and Gmail Login in another article. If you want to know more about it, then you can check here. We are covering the Facebook Login in this article. Now, we are going step by step. I have given my git repository link in the bottom as well.
 

Create a new Flutter Application 

 
The first and basic step is to create a new application in Flutter. If you are a beginner in Flutter, you can check my blog Create a first app in Flutter. I have created an app named as “flutter_fb_login” here.
 

Create a Facebook App in Facebook Developer Console

 
For Facebook Login in Flutter, you need to create a Facebook app in the Facebook Developer Console. For that, follow the below steps.
  1. Go here and login using your Facebook account or create a new one.
  2. Then, create a new app using MyApp => Create App, give an app name and create the app. Check out the below screenshot.

    Facebook Login in Flutter
    Facebook Login in Flutter

  3. After creating the app, click on "Integrate Facebook Login" and Confirm.
  4. Go to the Dashboard tab. Under "My Products", you will find Facebook Login=>Settings (click on that).
  5. Then, on the left side, you will find QuickStart under Facebook Login menu. Just click on it.
  6. Select Android.

    Facebook Login in Flutter

  7. On the next two screens, just click "Next". After that, you will get a screen asking for your Android project. Give the package name and default Activity Class name as I have given in the below screenshot. And go to Save => Use This Package => Continue.

    Facebook Login in Flutter

    Package Name: com.example.flutter_fb_login
    Default Activity: com.example.flutter_fb_login.MainActivity

  8. On the next screen, you need to add your development and release key hashes. Follow Mac or Windows as per your OS and enter the hash key. Please note that the default Android Keystore password is "android". Copy the hash key and paste there and go to Save => Continue.
  9. Now, click "Next".
  10. Next, you need to put a lot of stuff in your app.

    1. Go to your project's android/app/src/main/res/values folder. Under the Values folder, create a new file named strings.xml and put the below string (you have in your Facebook project ) in this file.
      1. <?xml version="1.0" encoding="utf-8"?>  
      2. <resources>  
      3.    <string name="app_name">flutter_login</string>  
      4.    <string name="facebook_app_id">2432431656989926</string>  
      5.    <string name="fb_login_protocol_scheme">fb2432431656989926</string>  
      6. </resources>  
    2. Then, go to android/app/src/main/AndroidManifest.xml and paste the below code (you have in your Facebook project) under first activity and in the application tag. Please check the screenshot for better undestanding.

      Facebook Login in Flutter

    3. Click "Next" for all further screens.
    4. You are all done with the Facebook App Setup. Congratulations…. :)

Set up a project in Google Firebase

 
Now, you need to set up a project in Google Firebase. Follow the below steps for that. Please follow the steps very carefully.
  1. Go here and add a new project. I will share the screenshot of how it looks so you will get a better idea.
  2. Click on "Add Project" to add a new project in Google Firebase. Then, you will find the below form.

    Facebook Login in Flutter

    Facebook Login in Flutter
     
  3. Give a project name and accept the terms and condition and click "Create Project". It will take some time to create a new project and redirect you to the Project Overview page.
  4. Now, you need to add an Android app to this project. You can add a new Android project by clicking on the Android icon. You can also add an iOS project if you want to create the iOS application for the same.

    Facebook Login in Flutter
     
  5. In Project Overview, add an Android app. For that, click on the Android icon. It will open a new form.

    Facebook Login in Flutter
     
  6. You will find the Android package name in the AndroidManifest.xml file in Android => App => main folder of your project.
  7. App nickname is optional
  8. For SHA-1 generation, go here.
  9. Now, download the google-service.json file and put in the Android => App folder of your project.
  10. Next, you need to configure some dependencies.

    Project-level build.gradle (<project>/build.gradle): means build.gradle file in the Android folder directly.
    1. buildscript {  
    2.     dependencies {  
    3.         // Add this line  
    4.         classpath 'com.google.gms:google-services:4.2.0'  
    5.     }  
    App-level build.gradle (<project>/<app-module>/build.gradle): means build.gradle file in Android = > App folder

    // Add to the bottom of the file
    apply plugin: 'com.google.gms.google-services’

    Note
    Don’t need to add implementation 'com.google.firebase:firebase-core:16.0.9' in dependencies

  11. In the next step, it will try to verify your app. For that, you need to run your app once or you can skip this step.
  12. Hurray! Your Android app has been created.

Enable Facebook Sign-In method in Firebase 

 
Now, you need to enable the Facebook Sign-In method in Firebase. For that, you need to go to the Authentication tab and then Sign-in method tab. From there, enable Facebook Sign-In method. Please check the screenshot.
 
Facebook Login in Flutter 
  1. You need an App ID and App secret. Get that from your Facebook app that you have created in previous steps. You will get the App Id and App secret from Settings => Basic. Note: Click on "Show App Secrete" to copy it.

    Facebook Login in Flutter

  2. Copy the OAuth redirect from the Firebase app and paste in Facebook App. Facebook Login=>Settings >> Valid OAuth Redirect URIs. Please check the below screenshot.

    Copy from Firebase App

    Facebook Login in Flutter

    Paste in Facebook App (Login=>Settings Valid OAuth Redirect URIs)

    Facebook Login in Flutter

  3. You are all done with Firebase Setup. Congratulations!!!

Dependency Setup in Firebase project 

 
Get back to the project and open the pubspec.yaml file in the root of the project. Pubspec.yaml is used to define all the dependencies and assets of the project.
  1. Add the below dependencies and save the file.

    firebase_auth:
    flutter_facebook_login:

  2. Please check the below screenshot so that you will get the idea of where to add the dependency.

    Facebook Login in Flutter

  3. Run the "flutter packages get" command in terminal OR if you are using Visual Studio Code, then after saving the file, it will automatically run the command.
  4. Now, we are done with all dependency setup at project side as well…. :)
Now, we need to programmatically handle the Facebook login in Google Firebase. For that, we create a page, login_page.dart. I have attached a link of Git repo at the bottom of the article; you can take reference from there. Here, I will just define the main logic of Facebook login and logout.

import'package:firebase_auth/firebase_auth.dart';
import'package:flutter_facebook_login/flutter_facebook_login.dart';

  1. Login using Facebook.
    1. Future < FirebaseUser > facebookLogin(BuildContext context) async {  
    2.         FirebaseUser currentUser;  
    3.         // fbLogin.loginBehavior = FacebookLoginBehavior.webViewOnly;  
    4.         // if you remove above comment then facebook login will take username and pasword for login in Webview  
    5.         try {  
    6.             final FacebookLoginResult facebookLoginResult = await fbLogin.logInWithReadPermissions(['email''public_profile']);  
    7.             if (facebookLoginResult.status == FacebookLoginStatus.loggedIn) {  
    8.                 FacebookAccessToken facebookAccessToken = facebookLoginResult.accessToken;  
    9.                 final AuthCredential credential = FacebookAuthProvider.getCredential(accessToken: facebookAccessToken.token);  
    10.                 final FirebaseUser user = await auth.signInWithCredential(credential);  
    11.                 assert(user.email != null);  
    12.                 assert(user.displayName != null);  
    13.                 assert(!user.isAnonymous);  
    14.                 assert(await user.getIdToken() != null);  
    15.                 currentUser = await auth.currentUser();  
    16.                 assert(user.uid == currentUser.uid);  
    17.                 return currentUser;  
    18.             } catch (e) {  
    19.                 print(e);  
    20.                 return currentUser;  
    21.             }  
    22.         }  
  2. Logout from Facebook.
    1. Future < bool > facebookLoginout() async {  
    2.     await auth.signOut();  
    3.     await fbLogin.logOut();  
    4.     return true;  
    5. }  
  3. When you sign up successfully, you can check that Google Firebase stores the user details on the server. Please check the screenshot.
Facebook Login in Flutter

You may encounter an error here, as mentioned below.

Error: import androidx.annotation.NonNull;

Solution

Put android.useAndroidX=true and android.enableJetifier=true in the android/gradle.properties file.
 
NOTE
  • I have commented one line in Facebook Sign-in method also. Try that by uncommenting it. 

    fbLogin.loginBehavior = FacebookLoginBehavior.webViewOnly;

  • There will be an upgrade in any plugin like firebase_auth or flutter_facebook_login. So, if you find an error during login, please refer to its official documentation.

  • Please check out the Git repo for full source code. You need to add your google-services.json file in Android => App folder. Also, add android/app/src/main/res/values/strings.Xml with your Facebook App name, App Id and Secret.

  • Git Repo

Conclusion

 
Google Firebase is a very good service provider in terms of data validation, data storing, realtime data, and push notifications. We have only used the Google Firebase Facebook Sign-in feature in this article. We can do more with  it. Stay tuned for more articles on Google Firebase and Flutter.