Why Use Firebase Authentication in Flutter?
Firebase Authentication is a scalable and secure solution to handle user authentication in mobile and web apps. Here’s why it’s a great choice:
- Multi-Provider Support: Includes email/password, Google, Facebook, Twitter, and Apple authentication.
- Ease of Integration: Designed for seamless integration with Flutter.
- Secure: Built-in security measures to safeguard user credentials.
- Real-Time Updates: Sync authentication states across devices and platforms.

Step 1: Setting Up Firebase for Your Flutter App
Before implementing authentication, you need to set up Firebase for your Flutter project.
1. Create a Firebase Project
- Go to the Firebase Console.
- Click Add Project and follow the steps to create a new project.
2. Add Your Flutter App to Firebase
- In the Firebase Console, go to Project Settings and add an app (Android and/or iOS).
- Download the configuration file:
- For Android:
google-services.json
- For iOS:
GoogleService-Info.plist
- For Android:
- Place the file in your app’s respective directories:
- Android:
android/app/
- iOS:
ios/Runner/
- Android:
3. Add Firebase SDK
- Update the
android/build.gradle
andandroid/app/build.gradle
files to include Firebase dependencies. - For iOS, ensure the
Podfile
includes Firebase pods.
4. Install Firebase Packages
In your pubspec.yaml
file, add the following dependencies:
dependencies:
firebase_core: ^2.12.1
firebase_auth: ^4.6.0
Run flutter pub get
to install the packages.
Step 2: Initialize Firebase in Flutter
Firebase needs to be initialized before use. Update your main.dart
file as follows:
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: AuthScreen(),
);
}
}
Step 3: Implement Firebase Authentication
Firebase Authentication supports multiple sign-in methods. Here’s how to implement them:
1. Email and Password Authentication
Enable Email/Password Sign-In in Firebase
- In the Firebase Console, navigate to Authentication > Sign-In Method.
- Enable Email/Password sign-in.
Sign Up New Users
import 'package:firebase_auth/firebase_auth.dart';
Future<void> signUp(String email, String password) async {
try {
UserCredential userCredential = await FirebaseAuth.instance.createUserWithEmailAndPassword(
email: email,
password: password,
);
print('User signed up: ${userCredential.user?.email}');
} catch (e) {
print('Error: $e');
}
}
Sign In Existing Users
Future<void> signIn(String email, String password) async {
try {
UserCredential userCredential = await FirebaseAuth.instance.signInWithEmailAndPassword(
email: email,
password: password,
);
print('User signed in: ${userCredential.user?.email}');
} catch (e) {
print('Error: $e');
}
}
Sign Out Users
Future<void> signOut() async {
await FirebaseAuth.instance.signOut();
print('User signed out');
}
2. Google Sign-In
Enable Google Sign-In in Firebase
- Go to Authentication > Sign-In Method and enable Google.
- For Android, configure the SHA-1 and SHA-256 keys in your Firebase project settings.
Install Google Sign-In Package
Add the google_sign_in
package to your pubspec.yaml
:
dependencies:
google_sign_in: ^6.1.3
Sign In with Google
import 'package:firebase_auth/firebase_auth.dart';
import 'package:google_sign_in/google_sign_in.dart';
Future<void> googleSignIn() async {
try {
final GoogleSignIn googleSignIn = GoogleSignIn();
final GoogleSignInAccount? googleUser = await googleSignIn.signIn();
if (googleUser != null) {
final GoogleSignInAuthentication googleAuth = await googleUser.authentication;
final OAuthCredential credential = GoogleAuthProvider.credential(
accessToken: googleAuth.accessToken,
idToken: googleAuth.idToken,
);
UserCredential userCredential = await FirebaseAuth.instance.signInWithCredential(credential);
print('User signed in: ${userCredential.user?.displayName}');
}
} catch (e) {
print('Error: $e');
}
}
Step 4: Monitor Authentication State
To track if a user is logged in or logged out, use FirebaseAuth’s authStateChanges
:
StreamBuilder<User?> buildAuthStream() {
return StreamBuilder<User?>(
stream: FirebaseAuth.instance.authStateChanges(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return CircularProgressIndicator();
} else if (snapshot.hasData) {
return HomeScreen(); // User is logged in
} else {
return LoginScreen(); // User is logged out
}
},
);
}
Step 5: Error Handling and Validation
Always handle errors gracefully and provide feedback to users:
try {
// Firebase operation
} on FirebaseAuthException catch (e) {
if (e.code == 'email-already-in-use') {
print('The account already exists for this email.');
} else if (e.code == 'wrong-password') {
print('Incorrect password.');
} else {
print('Error: ${e.message}');
}
}
Best Practices for Firebase Authentication
- Secure API Keys: Use Firebase App Check to prevent abuse of your API keys.
- Validate Input: Ensure form fields are properly validated before making Firebase calls.
- Log Out Inactive Users: Use session expiration or auto-logout mechanisms.
- Implement Custom Error Messages: Display user-friendly messages for authentication errors.
- Use Authentication Providers Wisely: Choose providers that align with your app’s audience (e.g., Google for global users, Apple for iOS users).
Conclusion
Firebase Authentication is a powerful, easy-to-use solution for managing user authentication in Flutter apps. With its support for multiple sign-in providers and seamless integration, you can create secure, user-friendly apps. Follow the steps outlined in this guide to integrate Firebase Authentication into your Flutter project and enhance the security and functionality of your app.


FAQs
Q1: Is Firebase Authentication free?
Yes, Firebase Authentication is free for basic usage. For advanced features, you may need to move to a paid plan.
Q2: Can I use Firebase Authentication with other backends?
Yes, Firebase Authentication works independently and can integrate with any backend.
Q3: How do I add multiple sign-in methods?
Enable the required providers in Firebase Console and implement their respective SDKs in your Flutter app.
Explore Other Flutter Topics…
- Introduction to Flutter and Dart
- Why choose Flutter
- Installing Flutter On Your Windows Mac And Linux System
- Your first Flutter app
- Flutter project structure
- Building blocks of Flutter
- Stateful vs. Stateless Widgets Explained
- Flutter layout system
- Flutter text widget
- Creating Buttons in Flutter: ElevatedButton, TextButton, and IconButton
- Handling User Input with Flutter Forms
- Container class in Flutter
- Flutter Navigation
- Flutter – Pass Data One Screen To Another Screen
- Managing Device Orientation in Flutter
- Stateful widget lifecycle in Flutter
- Future of Flutter
- Flutter Themes
- Flutter Animations
- Flutter AppBar Customization
- ListView in Flutter
- Flutter GridView
- Flutter Expanded Widget
- Flutter BottomNavigation Bar
- Floating Action Button
- Drawer Widgets in Flutter
- Form Validation in Flutter
- Flutter TextField
- Adding AdMob ads to a Flutter app
- Building Flutter Web & Desktop Applications
- What is Async and Await in Flutter
- HTTP requests in Flutter
- Parsing JSON in Flutter
- Tinder-Style Swipe Cards in Flutter
- Flutter Tic Tac Toe Game Tutorial
- Flutter Login UI Tutorial
- Flutter Card Widget Tutorial
- Flutter music player app tutorial
- Flutter introduction screens
- Shared Preferences in Flutter
- SQLite Database in Flutter
- Firebase Authentication in Flutter
- Firebase Firestore in Flutter
- Push Notifications in Flutter
- Handling File Uploads in Flutter
- Responsive Design in Flutter
- Provider in Flutter
- Riverpod in Flutter
- Flutter BLoC Pattern Tutorial