Flutter Facebook Authentication with Firebase

Social authentication such as Google and Facebook sign-in are user friendly methods to allow users to sign in to your apps within seconds.

Firebase Authentication provides pre-built methods to implement social authentication using Flutter. In this article, we’ll learn how to implement Flutter Facebook Authentication with Firebase.

So, without further ado, let’s dive right into it.

Table of Contents

1. Create Firebase project and set it up on required platforms

First of all, we need to create a new Firebase project and set it up on required platforms.

2. Enable authentication and Facebook sign-in method

From the Firebase dashboard, on the left side menu panel, click on Authentication then click Get started

Flutter facebook authentication with Firebase

then, select Facebook from the sign-in providers

Flutter facebook authentication with Firebase

After that, you’ll need to enable it and provide App ID and App secret. To get these, you’ll first need to create a Facebook project which we’ll be doing in the next step.

Flutter facebook authentication with Firebase

3. Create Facebook project

  •  Go to Facebook Developers and sign in with your Facebook account to start creating the Facebook project. Once you’re signed in, you’ll be directed to the dashboard.
  • From the dashboard, click Create AppFlutter facebook authentication with Firebase
  • Select consumer for the app type and click next Then enter the display name you want for your app.Flutter facebook authentication with Firebase
  • Now, copy the app ID from the Facebook app dashboard and paste it in the App ID section in Firebase console.Flutter facebook authentication with Firebase
  • Next you need to get the app secret. From the left menu, navigate to Setting > Basic then you will see your app secret. Copy it and add it to the Firebase console.Flutter facebook authentication with Firebase
  • Back to Facebook Developers, we need to enable Facebook Login. From the dashboard, find Facebook Login under products section and click set upFlutter facebook authentication with Firebase
  • Next, select Android platformFlutter facebook authentication with Firebase
  • Download the Facebook SDK for Android and click nextFlutter facebook authentication with Firebase
  • Import the Facebook SDK. In you project level build.gradle file, ensure that you add mavenCentral() repository if it’s not there.
    mavenCentral()
  • Then, in app-level build.gradle file, add the following implementation and click done then next

     

    implementation 'com.facebook.android:facebook-android-sdk:latest.release'
  • Next, add your project package name (i.e, com.example.name) then specify the default Activity class name by simple adding .MainActivity to the end of your package name (i.e, com.example.name.MainActivity). Once done, click save and continueFlutter facebook authentication with Firebase
  • Define your key hash. To do so, you can convert it online at here. All you have to do is to copy your SHA-1 key and pasting it after removing the colons from the key. Then, change the input type to Hex.  Copy the result and paste it in the key hash field in Facebook developers site and click save
    Flutter facebook authentication with FirebaseFlutter facebook authentication with Firebase
  • For the next step, you can skip it and click Next
  • Next, you need to edit the resources and Manifest file in your Flutter project. Copy the three lines of code provided then in your project navigate to android -> app -> src -> main -> res -> values and create a new resource file called strings.xml. Paste the code you copied between the resources tagsFlutter facebook authentication with FirebaseFlutter facebook authentication with Firebase
  • Then, you need to set up the values of the strings you added to the file.
    • copy your Facebook app ID and paste it in the facebook_app_id string.
    • To get the Facebook Client token, in the Facebook app Dashboard, navigate to Settings > Advanced > Security > Client token.
    • For the login protocol scheme add ‘fb’ in front of you Facebook app ID and add it the fb_login_protocol_shceme string
    • add another string as the following
      <string name="app_name"> Your app name </string>
Flutter facebook authentication with Firebase
  •  Next, you need to modify your Manifest file
    • open AndroidManifest.xml file and inside the application tag add the meta data provided and paste it
      <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id"/>
      <meta-data android:name="com.facebook.sdk.ClientToken" android:value="@string/facebook_client_token"/>
      Flutter facebook authentication with FirebaseFlutter facebook authentication with Firebase
    • Next, copy the activity code and paste it right before the closing tag of the application tag
    • Next, copy the permission code and paste right before the application tag
    • Once all these steps are done, click next in the Facebook developers
  • You can skip the following steps (7-10) as these are Java code which we’ll not be using in this tutorial.
  • Facebook Login is successfully enabled. Confirm that by going to the dashboard and checking that Facebook Login is listed under the products section. Also, try to run your project to ensure there are no errors and confirm all settings are successfully completed

4 Add Dependencies to Flutter Project

In pubspec.yaml file, add the following plugins to enable Firebase and Facebook Authentication.

firebase_core: ^1.14.1
flutter_facebook_auth: ^3.5.0
firebase_auth: ^3.3.14

5 Initialize Firebase App

In main.dart file, add the following code in the main method to initialize Firebase App and enables its features.

WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();

6 Implement Sign in with Facebook method

  • Create the login page
    First of all, create a new file called facebook_login.dart and inside it create a Stateful widget called FacebookLogin

     

    Scaffold(
      appBar: AppBar(
        title: const Text('Flutter Facebook Login'),
        centerTitle: true,
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
    
          Center(
            child: ElevatedButton(
                onPressed: (){
                  //signinWithFacebook
                  
                },
                child: Text('Log in'),
            ),
          ),
    
    
        ],
      )
    
    );
  • Create a method to sign in with Facebook
    Inside the facebook_login.dart file, create the following method

     

    Future<UserCredential> signInWithFacebook() async {
      
      final LoginResult loginResult = await FacebookAuth.instance.login(
        permissions: [
          'email', 'public_profile', 'user_birthday'
        ]
      );
    
      final OAuthCredential facebookAuthCredential = FacebookAuthProvider.credential(loginResult.accessToken!.token);
      return FirebaseAuth.instance.signInWithCredential(facebookAuthCredential);
    }
  • Call the signInWithFacebook method
    In the onPressed method of the Elevated button we created earlier, add the following code

     

    onPressed: (){
      signInWithFacebook();
      setState(() {
        Navigator.of(context).push(
          MaterialPageRoute(builder: (context) => Home())
        );
      });
    },
  • Create the home page
    create a new file called home.dart then create a Stateful widget called Home and add the following code

     

    Scaffold(
      body:  Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
    
              const Text('Welcome', style: TextStyle(color: Colors.black54, fontSize: 30),),
    
              const SizedBox(height: 30),
              ElevatedButton(
                onPressed: () async {
                  //sign out
                },
                child: const Text('Log out'),
              ),
    
            ],
          ),
      ),
    
    );

7 Implement Sign out method

In the home.dart file, add the following code inside onPressed method of the elevated button to enable sign out function

onPressed: () async {
  await FirebaseAuth.instance.signOut();

  await FacebookAuth.instance.logOut();
  setState(() {

    Navigator.of(context).pop();
  });
},

Conclusion

and there you have it, a complete guide on how to implement Flutter Facebook authentication with Firebase. I hope you enjoyed this tutorial and learnt from it. You can download the final source code from here.

If you want to learn more about Flutter Firebase, check out the following articles on Flutter Firebase phone authentication and Flutter Firebase Email authentication

Don’t forget to share this post with your friends who are interested in learning more about Firebase.

Oh hi there!
It’s nice to meet you.

Sign up to receive awesome content in your inbox, every month.

Let's Do This!

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top