Most of the time, you need to handle user authentication in your Flutter apps. Now, you already know how to integrate Firebase Firestore for real-time data syncing. The next step we are going to learn how to use the user authentication system with Firebase Authentication. Firebase Authentication supports several common methods for signing users in, including email or password and popular social logins such as Google, Facebook, Twitter, and more.
In this tutorial, we won’t cover every single method but instead we will focus on adding Google and Facebook authentication to your Flutter app. With these implementation, user can choose using their existing Google and Facebook account to sign up the apps. For sure you can encourage the users sign up with their own email, it always up to you.
What You Will Learn in this tutorial:
- Setting up Google and Facebook login in Firebase.
- Implementing Google and Facebook sign-in in Flutter.
- Managing user sessions with Firebase.
Let’s get started.
Setting Up Social Providers in Firebase
Google Sign-In Setup
In Firebase, you need to enable Google Sign-In for your Flutter app, the steps are straightforward. Follow these steps in the Firebase Console:
Go to Authentication under the “Build” section in the Firebase Console.
Navigate to the Sign-in method tab.
Enable Google as a provider.
You don’t really need to configure much here, as Firebase handles most of the setup for you, that’s it, easy 🙂
Facebook Sign-In Setup
For Facebook social login, it’s pretty much the same. But you need to first set up a Facebook App:
Go to Facebook for Developers.
Create a new app in the Facebook Developer Console.
In the Facebook Login section, configure the following:
- Add your app’s OAuth redirect URIs (available in Firebase’s Authentication settings).
- Retrieve your App ID and App Secret from the Facebook Developer Console.
Next, go back to the Firebase Console:
- Go to Authentication and enable Facebook as a provider.
- Paste the App ID and App Secret from your Facebook Developer App.
Add Social Login Dependencies in Flutter
Now, the basic configuration has been done. Next move back to your Flutter project. In your pubspec.yaml
, add the necessary dependencies for Firebase Authentication, Google, and Facebook sign-ins, as shown below:
dependencies:
firebase_core: latest_version
firebase_auth: latest_version
google_sign_in: latest_version
flutter_facebook_auth: latest_version
Remember, after adding the packages, you need to run flutter pub get
to install the dependencies.
Implement Google Sign-In in Flutter
Next, double confirm you have already enabled Google Sign-In in Firebase and added the required packages. Then you can start implement the Google login in Flutter app.
Set Up Google Sign-In in main file
Open your lib/main.dart
file and set up Firebase and Google Sign-In:
import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:google_sign_in/google_sign_in.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: GoogleSignInScreen(),
);
}
}
class GoogleSignInScreen extends StatefulWidget {
@override
_GoogleSignInScreenState createState() => _GoogleSignInScreenState();
}
class _GoogleSignInScreenState extends State<GoogleSignInScreen> {
final FirebaseAuth _auth = FirebaseAuth.instance;
final GoogleSignIn _googleSignIn = GoogleSignIn();
Future<void> _signInWithGoogle() async {
try {
final GoogleSignInAccount? googleUser = await _googleSignIn.signIn();
if (googleUser == null) {
// User canceled the sign-in
return;
}
final GoogleSignInAuthentication googleAuth = await googleUser.authentication;
final OAuthCredential credential = GoogleAuthProvider.credential(
accessToken: googleAuth.accessToken,
idToken: googleAuth.idToken,
);
final UserCredential userCredential = await _auth.signInWithCredential(credential);
print('User signed in: ${userCredential.user?.displayName}');
} catch (e) {
print('Error signing in with Google: $e');
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Google Sign-In')),
body: Center(
child: ElevatedButton(
onPressed: _signInWithGoogle,
child: Text('Sign In with Google'),
),
),
);
}
}
In this program, GoogleSignInAccount represents the Google account that the user signs in with. App user can make use of their credentials from Google to sign in with Firebase. The Google sign-in button initiates the sign-in process when pressed.
Configure Android and iOS for Google Sign-In
Android: In the Firebase Console, download the updated google-services.json
file (if not done previously) and place it in the android/app
directory. Then open android/app/build.gradle
and ensure the following dependencies are included:
apply plugin: 'com.google.gms.google-services'
iOS: For Apple, add the updated GoogleService-Info.plist
to the ios/Runner
directory. Open Xcode, go to Signing & Capabilities, and add Google Sign-In to your app. That’s it.
Implement Facebook Sign-In in Flutter
Now that we’ve handled Google Sign-In, let’s implement Facebook Login.
1. Set Up Facebook Sign-In in main.dart
Add the following code to your main.dart
file to handle Facebook Login:
import 'package:flutter_facebook_auth/flutter_facebook_auth.dart';
class FacebookSignInScreen extends StatefulWidget {
@override
_FacebookSignInScreenState createState() => _FacebookSignInScreenState();
}
class _FacebookSignInScreenState extends State<FacebookSignInScreen> {
final FirebaseAuth _auth = FirebaseAuth.instance;
Future<void> _signInWithFacebook() async {
try {
final LoginResult result = await FacebookAuth.instance.login();
if (result.status == LoginStatus.success) {
final OAuthCredential facebookCredential =
FacebookAuthProvider.credential(result.accessToken!.token);
final UserCredential userCredential =
await _auth.signInWithCredential(facebookCredential);
print('User signed in with Facebook: ${userCredential.user?.displayName}');
} else if (result.status == LoginStatus.cancelled) {
print('User cancelled Facebook login');
} else {
print('Error: ${result.message}');
}
} catch (e) {
print('Error signing in with Facebook: $e');
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Facebook Sign-In')),
body: Center(
child: ElevatedButton(
onPressed: _signInWithFacebook,
child: Text('Sign In with Facebook'),
),
),
);
}
}
This code uses flutter_facebook_auth
to handle Facebook login:
- The
LoginResult
object indicates the login status (success, canceled, or error). - After successful login, the Facebook credential is used to authenticate with Firebase.
2. Configure Android and iOS for Facebook Login
Android
- In the Facebook Developer Console, add your Android key hash.
- Ensure your
AndroidManifest.xml
file includes the necessary Facebook permissions and meta-data:
<uses-permission android:name="android.permission.INTERNET"/>
<meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id"/>
iOS
- In Xcode, open Info.plist and add your Facebook App ID and other required settings:
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLSchemes</key>
<array>
<string>fb{YOUR_FACEBOOK_APP_ID}</string>
</array>
</dict>
</array>
Step 5: Managing User Sessions
Once users sign in using either Google or Facebook, you can manage their sessions in Firebase. Here’s how you can check if a user is already logged in:
class HomeScreen extends StatelessWidget {
final FirebaseAuth _auth = FirebaseAuth.instance;
@override
Widget build(BuildContext context) {
final User? user = _auth.currentUser;
if (user != null) {
return Scaffold(
appBar: AppBar(title: Text('Welcome ${user.displayName}')),
body: Center(child: Text('You are logged in!')),
);
} else {
return Scaffold(
appBar: AppBar(title: Text('Sign In')),
body: Center(child: Text('Please sign in')),
);
}
}
}
- currentUser: Retrieves the currently signed-in user, allowing you to display personalized content or route users to the appropriate screen.
Best Practices for Social Login
- Fallback to Email Login: Not all users prefer social logins. Always provide an email/password option as a fallback.
- User Privacy: Make sure you ask for minimal permissions when using Facebook login and adhere to privacy policies.
- Logout Handling: Implement a clear logout option using
_auth.signOut()
to allow users to end their session easily.
Conclusion: Enhancing User Authentication with Social Logins
In this tutorial, you’ve learned how to integrate Google and Facebook login into your Flutter app using Firebase Authentication. Social logins reduce the barrier for entry, making it easier for users to sign up and sign in quickly. You now have the foundation to build a robust authentication system that supports both traditional email/password methods and modern social logins.
In the next tutorial, we’ll explore advanced Firestore queries and how to structure data for scalability in a real-world application. Keep building, and happy coding!