How to Login Facebook in Flutter

Introduction

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

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.

This is image title

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

This is image title

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

This is image title

Package Name: com.example.flutter_fb_login
Default Activity: com.example.flutter_fb_login.MainActivity
  1. 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.
  2. Now, click “Next”.
  3. Next, you need to put a lot of stuff in your app.

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

<?xml version="1.0" encoding="utf-8"?>  
<resources>  
   <string name="app_name">flutter_login</string>  
   <string name="facebook_app_id">2432431656989926</string>  
   <string name="fb_login_protocol_scheme">fb2432431656989926</string>  
</resources>  

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

This is image title

10.3. Click “Next” for all further screens.
10.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.

This is image title

This is image title

  1. 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.
  2. 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.

This is image title

  1. In Project Overview, add an Android app. For that, click on the Android icon. It will open a new form.

This is image title

  1. You will find the Android package name in the AndroidManifest.xml file in Android => App => main folder of your project.
  2. App nickname is optional
  3. For SHA-1 generation, go here.
  4. Now, download the google-service.json file and put in the Android => App folder of your project.
  5. Next, you need to configure some dependencies.
Project-level build.gradle (/build.gradle): means build.gradle file in the Android folder directly.
	
	```
	buildscript {  
dependencies {  
    // Add this line  
    classpath 'com.google.gms:google-services:4.2.0'  
}  
	```
App-level build.gradle (//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
  1. 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.
  2. 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.

This is image title

  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.

This is image title

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

    ![This is image title](https://www.c-sharpcorner.com/article/facebook-login-in-flutter/Images/Facebook%20Login%20in%20Flutter12.png "This is image title")
    

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

    ![This is image title](https://www.c-sharpcorner.com/article/facebook-login-in-flutter/Images/Facebook%20Login%20in%20Flutter13.png "This is image title")
    
  2. 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.

This is image title

  1. 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.
  2. 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.
Future < FirebaseUser > facebookLogin(BuildContext context) async {  
        FirebaseUser currentUser;  
        // fbLogin.loginBehavior = FacebookLoginBehavior.webViewOnly;  
        // if you remove above comment then facebook login will take username and pasword for login in Webview  
        try {  
            final FacebookLoginResult facebookLoginResult = await fbLogin.logInWithReadPermissions(['email', 'public_profile']);  
            if (facebookLoginResult.status == FacebookLoginStatus.loggedIn) {  
                FacebookAccessToken facebookAccessToken = facebookLoginResult.accessToken;  
                final AuthCredential credential = FacebookAuthProvider.getCredential(accessToken: facebookAccessToken.token);  
                final FirebaseUser user = await auth.signInWithCredential(credential);  
                assert(user.email != null);  
                assert(user.displayName != null);  
                assert(!user.isAnonymous);  
                assert(await user.getIdToken() != null);  
                currentUser = await auth.currentUser();  
                assert(user.uid == currentUser.uid);  
                return currentUser;  
            } catch (e) {  
                print(e);  
                return currentUser;  
            }  
        }  
  1. Logout from Facebook.
Future < bool > facebookLoginout() async {  
    await auth.signOut();  
    await fbLogin.logOut();  
    return true;  
}  
  1. When you sign up successfully, you can check that Google Firebase stores the user details on the server. Please check the screenshot.

This is image title

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

Thank you for reading!

#Flutter #Google Firebase #Facebook #Login #flutter

How to Login Facebook in Flutter
99.65 GEEK