Integrating Facebook Authentication into your Flutter app using Firebase allows users to sign in with their Facebook credentials, creating a seamless login experience. In this blog, we will go through a step-by-step guide to set up Facebook authentication using Firebase in a Flutter app.
Prerequisites
Before starting, ensure you have:
- Flutter installed on your machine.
- A Firebase project set up.
- A Facebook Developer account.
Step 1: Create a Firebase Project
- Go to the Firebase Console.
- Click Add Project and follow the steps to create a new project.
- Once the project is created, navigate to the Authentication section in Firebase and enable Facebook as a sign-in method.
Step 2: Set Up Facebook Developer App
- Go to the Facebook Developers site.
- Click on My Apps and then Create App.
- Choose the app type as Consumer, then click Next.
- Fill in the necessary details like App Name, App Contact Email, and choose a category. Then click Create App ID.
- In the Add a Product section, select Facebook Login and then click Set up.
Step 3: Configure Facebook Login
- In the Facebook Login section, select Settings.
- Under Valid OAuth Redirect URIs, add the following URL:
https://<your-firebase-project-id>.firebaseapp.com/__/auth/handler
- Go to Basic Settings and copy your App ID and App Secret.
Step 4: Enable Facebook Auth in Firebase
- Navigate back to your Firebase Console.
- In the Authentication section, go to the Sign-in Method tab.
- Enable Facebook and paste your App ID and App Secret from the Facebook Developer Console.
Step 5: Add Facebook SDK to Flutter Project
Open your Flutter project, and add the following dependencies to your pubspec.yaml
file:
yaml
dependencies: firebase_core: latest_version firebase_auth: latest_version flutter_facebook_auth: latest_version
Then, run:
flutter pub get
Step 6: Configure Firebase for Flutter
- Download the
google-services.json
file from the Firebase Console under Project Settings > General and place it in your Flutter project underandroid/app
. - Open
android/app/build.gradle
and add the following inside thedependencies
section:
gradle
implementation platform('com.google.firebase:firebase-bom:latest_version') implementation 'com.google.firebase:firebase-auth'
- In
android/build.gradle
, add:
classpath 'com.google.gms:google-services:latest_version'
- Add the following at the bottom of
android/app/build.gradle
:
apply plugin: 'com.google.gms.google-services'
Step 7: Initialize Firebase in Flutter
Open your Flutter project’s main.dart
file and initialize Firebase in the main()
function:
import 'package:firebase_core/firebase_core.dart'; import 'package:flutter/material.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp(); runApp(MyApp()); }
Step 8: Implement Facebook Login Functionality
Now, let’s implement the Facebook authentication logic. Create a new service or place this code inside a widget:
import 'package:flutter_facebook_auth/flutter_facebook_auth.dart'; import 'package:firebase_auth/firebase_auth.dart'; class FacebookAuthService { final FirebaseAuth _auth = FirebaseAuth.instance; Future<User?> signInWithFacebook() async { // Trigger the Facebook login process final LoginResult result = await FacebookAuth.instance.login(); if (result.status == LoginStatus.success) { // Get the access token final AccessToken accessToken = result.accessToken!; // Create a credential for Firebase Authentication final OAuthCredential credential = FacebookAuthProvider.credential(accessToken.token); // Sign in with the credential final UserCredential userCredential = await _auth.signInWithCredential(credential); return userCredential.user; } else { throw Exception('Failed to sign in with Facebook: ${result.message}'); } } Future<void> signOut() async { await FacebookAuth.instance.logOut(); await _auth.signOut(); } }
Step 9: Add Facebook Login Button
To add a Facebook login button in your app, use a simple button widget and link it to the Facebook login functionality:
import 'package:flutter/material.dart'; import 'facebook_auth_service.dart'; class LoginPage extends StatelessWidget { final FacebookAuthService _facebookAuthService = FacebookAuthService(); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text('Login')), body: Center( child: ElevatedButton( onPressed: () async { try { User? user = await _facebookAuthService.signInWithFacebook(); if (user != null) { print('Successfully logged in: ${user.displayName}'); } } catch (e) { print(e); } }, child: Text('Login with Facebook'), ), ), ); } }
Step 10: Test Your App
Once everything is in place, run your app on an emulator or physical device:
flutter run
Try logging in using Facebook and see if it successfully authenticates via Firebase.
Conclusion
Integrating Facebook authentication in Flutter using Firebase provides a seamless login experience for users. This guide covered all the steps to set up Facebook Login, from creating a Facebook developer app to configuring Firebase and implementing the login flow in Flutter.
By following these steps, you’ll be able to add Facebook authentication to your Flutter app quickly and efficiently. If you encounter any issues or have further questions, feel free to leave a comment or consult the documentation.
Happy coding!