Implementing Firebase Integration
1. Setting Up Firebase Project
Example: Firebase Project Setup
flutter create my_flutter_app
cd my_flutter_app
flutter pub add firebase_core
flutter pub add cloud_firestore
| Step | Description | Action |
|---|---|---|
| 1. Create Project | Create a new Flutter project | flutter create my_flutter_app |
| 2. Add Firebase Core | Initialize Firebase in your app | flutter pub add firebase_core |
| 3. Add Firestore | Add Cloud Firestore to your project | flutter pub add cloud_firestore |
Note: Ensure you have Firebase CLI installed and configured.
Warning: Make sure to add your Firebase configuration files (google-services.json for Android, GoogleService-Info.plist for iOS) to the appropriate directories in your project.
2. Adding Firebase to Flutter
Example: Add Firebase to Flutter Project
dependencies:
firebase_core: ^2.15.0
cloud_firestore: ^4.8.0
firebase_auth: ^4.6.0
| Dependency | Version | Description |
|---|---|---|
| firebase_core | ^2.15.0 |
Core Firebase SDK for Flutter |
| cloud_firestore | ^4.8.0 |
Firebase Cloud Firestore integration |
| firebase_auth | ^4.6.0 |
Firebase Authentication integration |
Note: Ensure you have Firebase project setup and
google-services.json (Android) or GoogleService-Info.plist (iOS) in your project.
Setup Workflow
- Initialize Firebase project in Firebase Console
- Add
firebase_coreto pubspec.yaml - Run
flutter pub get - Initialize Firebase in your app's main function
- Configure platform-specific files (Android/iOS)
3. Initializing Firebase
Initializing Firebase in a Flutter app involves setting up the Firebase configuration and ensuring the Firebase SDK is properly integrated into your project.
| Step | Description | Code Example |
|---|---|---|
| 1. Add Firebase to Project | Include Firebase dependencies in your pubspec.yaml file. |
|
| 2. Get Firebase Configuration | Download google-services.json (Android) or GoogleService-Info.plist (iOS) from Firebase Console. |
flutter pub get |
| 3. Initialize Firebase | Call FirebaseApp.initializeApp() in your app's entry point. |
|
Note: Ensure Firebase is initialized before using any Firebase services to avoid runtime errors.
4. Configuring Android
Note: Ensure you have the latest version of Flutter and Firebase plugins installed.
| Step | Description | Action |
|---|---|---|
| 1 | Update android/app/src/main/AndroidManifest.xml |
Add Internet permission inside <manifest> tag:
<uses-permission android:name="android.permission.INTERNET" />
|
| 2 | Download google-services.json |
From Firebase Console, place in android/app/ directory. |
| 3 | Apply Firebase plugin in android/build.gradle |
Add to the top of the file:
|
| 4 | Update android/app/build.gradle |
Add inside dependencies block:
|
Example: Firebase Initialization
import 'package:firebase_core/firebase_core.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
5. Configuring iOS
Note: Ensure you have completed the Firebase project setup and downloaded the
GoogleService-Info.plist file before proceeding.| Step | Description | Action |
|---|---|---|
| 1 | Place the GoogleService-Info.plist file |
Drag and drop the file into your Xcode project navigator under the Runner target. |
| 2 | Update Info.plist |
Add the following to your Info.plist file inside the <dict> tag:
|
| 3 | Update Podfile |
Add the Firebase pod to your Podfile:
pod 'Firebase/Analytics'
|
| 4 | Install pods | Run the following command in your project's root directory:
cd ios && pod install
|
Example: Firebase Initialization in AppDelegate
import UIKit
import Firebase
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
FirebaseApp.configure()
return true
}
}
Warning: If you're using Firebase Analytics, ensure that
FirebaseAppDelegateProxyEnabled is set to false in Info.plist to avoid conflicts with custom app delegate logic.6. Using Firebase Authentication
Firebase Authentication provides a robust way to handle user authentication in Flutter apps. It supports various authentication methods including email/password, phone number, and third-party providers like Google, Facebook, and GitHub.
| Feature | Description | Notes |
|---|---|---|
| Email/Password | Allows users to sign in with email and password. | Supports password reset and email verification. |
| Phone Number | Authenticates users via SMS verification. | Requires Firebase Phone Auth integration. |
| Google Sign-In | Uses Google account credentials for authentication. | Requires Firebase Google Sign-In configuration. |
| Facebook Login | Authenticates users through Facebook. | Needs Firebase Facebook login setup. |
Example: Firebase Authentication Setup
// Import Firebase Auth package
import 'package:firebase_auth/firebase_auth.dart';
// Initialize FirebaseAuth instance
final FirebaseAuth auth = FirebaseAuth.instance;
// Sign in with email and password
Future<UserCredential> signInWithEmail(String email, String password) async {
try {
final UserCredential userCredential = await auth.signInWithEmailAndPassword(
email: email,
password: password,
);
return userCredential;
} catch (e) {
print('Sign-in error: $e');
rethrow;
}
}
// Create a new user with email and password
Future<UserCredential> createUserWithEmail(String email, String password) async {
try {
final UserCredential userCredential = await auth.createUserWithEmailAndPassword(
email: email,
password: password,
);
return userCredential;
} catch (e) {
print('User creation error: $e');
rethrow;
}
}
Example: Google Sign-In Integration
// Import Google Sign-In package
import 'package:google_sign_in/google_sign_in.dart';
// Initialize Google Sign-In
final GoogleSignIn googleSignIn = GoogleSignIn();
// Handle sign-in with Google
Future<UserCredential> signInWithGoogle() async {
try {
final GoogleSignInAccount? googleUser = await googleSignIn.signIn();
if (googleUser == null) return Future.error('Sign-in cancelled');
final GoogleSignInAuthentication googleAuth = await googleUser.authentication;
final OAuthCredential credential = GoogleAuthProvider.credential(
accessToken: googleAuth.accessToken,
idToken: googleAuth.idToken,
);
final UserCredential userCredential = await auth.signInWithCredential(credential);
return userCredential;
} catch (e) {
print('Google sign-in error: $e');
rethrow;
}
}
Note: Ensure Firebase Authentication is enabled in your Firebase Console before implementing these features.
Warning: Never store sensitive credentials like passwords in plain text. Always use secure storage methods or Firebase's built-in authentication mechanisms.
7. Using Cloud Firestore
Example: Basic Firestore Setup
// Import the Firebase package
import 'package:cloud_firestore/cloud_firestore.dart';
// Initialize Firestore
final FirebaseFirestore db = FirebaseFirestore.instance;
// Reference to a collection
CollectionReference users = db.collection('users');
| Property | Description | Usage |
|---|---|---|
| collection() | Creates a reference to a Firestore collection | db.collection('users') |
| doc() | Creates a reference to a Firestore document | db.collection('users').doc('user123') |
| get() | Retrieves a document or collection | users.get() |
| set() | Sets data for a document | userDoc.set({'name': 'John'}) |
| update() | Updates specific fields in a document | userDoc.update({'age': 30}) |
| delete() | Deletes a document | userDoc.delete() |
Note: Firestore requires Firebase initialization before use.
Example: Querying Documents
// Query users with age greater than 25
QuerySnapshot querySnapshot = await db.collection('users')
.where('age', isGreaterThan: 25)
.get();
// Iterate through results
for (var doc in querySnapshot.docs) {
print(doc['name']);
}
Example: Real-time Updates
// Listen for real-time changes
db.collection('users').snapshots().listen((snapshot) {
for (var doc in snapshot.docs) {
print('User: ${doc['name']}');
}
});
8. Using Firebase Storage
Firebase Storage is a cloud storage solution for Flutter apps, allowing you to store and serve user-generated content like images, videos, and files.
| Property | Description | Values |
|---|---|---|
| ref | Reference to a Firebase Storage location | StorageReference |
| putFile | Uploads a file to Firebase Storage | Future<StorageTaskSnapshot> |
| getDownloadURL | Retrieves the download URL of a file | Future<String> |
Example: Uploading a File to Firebase Storage
// Import the Firebase Storage package
import 'package:firebase_storage/firebase_storage.dart';
// Create a reference to the file you want to upload
StorageReference storageRef = FirebaseStorage.instance.ref().child('images/my_image.jpg');
// Upload the file
Future<StorageTaskSnapshot> uploadTask = storageRef.putFile(File('/path/to/my/image.jpg'));
// Handle the result
uploadTask.then((StorageTaskSnapshot snapshot) {
print('Upload completed');
});
Example: Retrieving a Download URL
// Get the download URL for a file
StorageReference storageRef = FirebaseStorage.instance.ref().child('images/my_image.jpg');
storageRef.getDownloadURL().then((String url) {
print('Download URL: $url');
});
Note: Ensure that Firebase Storage rules are configured to allow read and write access as needed.
Warning: Large file uploads may take time and should be handled asynchronously to avoid blocking the UI.
9. Using Firebase Messaging
Firebase Cloud Messaging (FCM) enables you to send messages and notifications to your Flutter app. It supports both iOS and Android platforms.
| Feature | Description | Notes |
|---|---|---|
| firebase_messaging | ^14.7.0 |
Official Firebase Messaging SDK for Flutter |
| onMessage | Future<void> |
Handles messages when the app is in the foreground |
| onBackgroundMessage | Future<void> |
Handles messages when the app is in the background or terminated |
| requestPermission | Future<bool> |
Requests permission to receive notifications |
Example: Requesting Notification Permission
import 'package:firebase_messaging/firebase_messaging.dart';
Future<void> requestNotificationPermission() async {
NotificationSettings settings = await FirebaseMessaging.requestPermission(
alert: true,
announcement: false,
badge: true,
carPlay: false,
criticalAlert: false,
provisional: false,
sound: true,
);
if (settings.authorizationStatus == AuthorizationStatus.authorized) {
print('User granted permission');
} else if (settings.authorizationStatus == AuthorizationStatus.denied) {
print('User denied permission');
}
}
Example: Handling Foreground Messages
import 'package:firebase_messaging/firebase_messaging.dart';
void main() {
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
print('Got a message whilst in the foreground!');
print('Message data: ${message.data}');
});
}
Example: Handling Background Messages
import 'package:firebase_messaging/firebase_messaging.dart';
Future<void> backgroundHandler(RemoteMessage message) async {
await Firebase.initializeApp();
print('Handling a background message: ${message.messageId}');
}
void main() {
FirebaseMessaging.onBackgroundMessage(backgroundHandler);
}
Note: Ensure that you have added the necessary configurations in your
android/app/src/main/AndroidManifest.xml and ios/Runner/Info.plist files for FCM to work correctly.
Warning: On iOS, you must enable the
Push Notifications capability in Xcode for FCM to function properly.
Key Points
- Use
requestPermission()to ask users for notification access - Implement
onMessagefor foreground handling - Implement
onBackgroundMessagefor background handling - Ensure proper setup in native project files (Android/iOS)
10. Using Firebase Analytics
Example: Initializing Firebase Analytics
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_analytics/firebase_analytics.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
| Property | Description | Usage |
|---|---|---|
| FirebaseAnalytics | Core class for Firebase Analytics integration | Used to log events and set user properties |
| logEvent | Logs a custom event to Firebase Analytics | Accepts event name and parameters |
| setUserId | Sets the user ID for analytics | Useful for tracking specific users |
Note: Ensure Firebase is initialized before using Analytics.
Warning: Events must be logged after Firebase is initialized.