Hi, Flutter Devs, If you’re like me, you’ve probably spent hours trying to figure out how to connect Firebase with Flutter without breaking your brain. I know the struggle — one minute you’re setting up login; the next you’re lost in a sea of settings and strange errors.
That’s why I made this cheat sheet! It’s a fun and simple list of all the important Firebase features you can use in your Flutter app. I’ve added short descriptions, and just enough info to save your time (and your sanity).
Table of Contents
1. Install Firebase in Flutter
Initialize Firebase in your Flutter project for backend services. Add dependencies and call Firebase.initializeApp().
1.Install Firebase CLI
npm install -g firebase-tools
firebase login
2. Initialize Firebase:
firebase init
3. Install Dependencies:
Add required dependencies in pubspec.yaml:
dependencies:
firebase_core: latest_version
firebase_auth: latest_version
cloud_firestore: latest_version
firebase_storage: latest_version
firebase_messaging: latest_version
4. Run flutter pub get
5. Initialize Firebase in main.dart
import 'package:firebase_core/firebase_core.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
2. Firebase Authentication
Authenticate users via email, Google, Facebook, Apple, and anonymous sign-in. Securely manage user sessions and identity.
Sign Up with Email & Password
Future signUp(String email, String password) async {
try {
UserCredential userCredential = await FirebaseAuth.instance.createUserWithEmailAndPassword(
email: email,
password: password,
);
print("User registered: ${userCredential.user?.uid}");
} catch (e) {
print("Error: $e");
}
}
Sign In with Email & Password
Future signIn(String email, String password) async {
try {
UserCredential userCredential = await FirebaseAuth.instance.signInWithEmailAndPassword(
email: email,
password: password,
);
print("User signed in: ${userCredential.user?.uid}");
} catch (e) {
print("Error: $e");
}
}
Sign Out
Future signOut() async {
await FirebaseAuth.instance.signOut();
print("User signed out");
}
3. Cloud Firestore (Database)
Add Data to Firestore
Future addUser(String userId, String name, int age) async {
await FirebaseFirestore.instance.collection('users').doc(userId).set({
'name': name,
'age': age,
});
}
Read Data from Firestore
Future getUser(String userId) async {
DocumentSnapshot doc = await FirebaseFirestore.instance.collection('users').doc(userId).get();
if (doc.exists) {
print("User data: ${doc.data()}");
} else {
print("User not found");
}
}
Update Data in Firestore
Future updateUser(String userId, String newName) async {
await FirebaseFirestore.instance.collection('users').doc(userId).update({
'name': newName,
});
}
Delete Data from Firestore
Future deleteUser(String userId) async {
await FirebaseFirestore.instance.collection('users').doc(userId).delete();
}
Need a handy guide to get the most out of Flutter widgets? Take a look at this Flutter Widget Cheat Sheet for easy access to all the essentials.
4. Firebase Cloud Storage (File Upload)
Store and manage user-generated files like images, PDFs, and videos. Secure access using Storage Security Rules.
Upload a File
Future uploadFile(File file) async {
Reference ref = FirebaseStorage.instance.ref().child('uploads/${file.path.split('/').last}');
await ref.putFile(file);
String downloadUrl = await ref.getDownloadURL();
print("File uploaded: $downloadUrl");
}
Download a File URL
Future getFileUrl(String filePath) async {
String url = await FirebaseStorage.instance.ref(filePath).getDownloadURL();
return url;
}
5. Firebase Cloud Messaging (Push Notifications)
Send real-time push notifications to users across platforms. Supports topic-based and token-based messaging.
Request Permission
Future requestPermission() async {
FirebaseMessaging messaging = FirebaseMessaging.instance;
NotificationSettings settings = await messaging.requestPermission();
print("Permission granted: ${settings.authorizationStatus}");
}
Get Firebase Token
Future getToken() async {
String? token = await FirebaseMessaging.instance.getToken();
print("FCM Token: $token");
}
Handle Incoming Messages
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
print("New notification: ${message.notification?.title} - ${message.notification?.body}");
});
6. Firebase Crashlytics
Track, diagnose, and fix crashes in real-time. Helps maintain app stability by highlighting common crash patterns.
Enable Crashlytics
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
FlutterError.onError = FirebaseCrashlytics.instance.recordFlutterError;
runApp(MyApp());
}
Manually Log Errors
try {
throw Exception("Test Error");
} catch (e, stack) {
FirebaseCrashlytics.instance.recordError(e, stack);
}
7. Firebase Performance Monitoring
Measure your app’s performance from real users. Tracks slow renders, network delays, and app startup time.
Enable Performance Monitoring
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
FirebasePerformance.instance;
runApp(MyApp());
}
Custom Performance Tracing
final Trace myTrace = FirebasePerformance.instance.newTrace("custom_trace");
await myTrace.start();
// Your performance-intensive task here
await myTrace.stop();
8. Firebase Remote Config
Update app content and behavior remotely without app updates. Ideal for feature toggles and A/B testing.
Fetch and Activate Remote Config
Future fetchRemoteConfig() async {
final remoteConfig = FirebaseRemoteConfig.instance;
await remoteConfig.fetchAndActivate();
print("Remote Config Value: ${remoteConfig.getString('welcome_message')}");
}
9. Firebase Dynamic Links (Deep Linking)
Create links that survive app installation and direct users to specific content. Works seamlessly across Android and iOS.
Generate a Short Dynamic Link
Future createDynamicLink(String link) async {
final DynamicLinkParameters parameters = DynamicLinkParameters(
uriPrefix: "https://yourapp.page.link",
link: Uri.parse(link),
androidParameters: AndroidParameters(
packageName: "com.example.app",
minimumVersion: 1,
),
iosParameters: IOSParameters(
bundleId: "com.example.app",
minimumVersion: "1.0.0",
),
);
final ShortDynamicLink shortLink = await FirebaseDynamicLinks.instance.buildShortLink(parameters);
return shortLink.shortUrl.toString();
}
Handle Incoming Dynamic Links
void handleDynamicLinks() {
FirebaseDynamicLinks.instance.onLink.listen((PendingDynamicLinkData? dynamicLink) {
final Uri? deepLink = dynamicLink?.link;
if (deepLink != null) {
print("Navigating to: ${deepLink.toString()}");
}
});
}
10. Firebase In-App Messaging
Send targeted in-app messages based on user behavior. Great for onboarding, promotions, and feature announcements.
Enable In-App Messaging
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
FirebaseInAppMessaging.instance.triggerEvent("app_launch");
runApp(MyApp());
}
Trigger a Custom Event
FirebaseInAppMessaging.instance.triggerEvent("special_offer");
11. Firebase Realtime Database
A cloud-hosted NoSQL database for syncing data in real-time. Ideal for chat apps, live updates, and games.
Write Data to Realtime Database
Future writeData() async {
DatabaseReference ref = FirebaseDatabase.instance.ref("users/123");
await ref.set({
"name": "John Doe",
"age": 25,
"email": "john@example.com",
});
}
Read Data from Realtime Database
Future readData() async {
DatabaseReference ref = FirebaseDatabase.instance.ref("users/123");
DataSnapshot snapshot = await ref.get();
if (snapshot.exists) {
print("User data: ${snapshot.value}");
} else {
print("No data found");
}
}
12. Firebase App Check (Security)
Protect backend resources from abuse by verifying app integrity. Blocks unwanted traffic from unauthorized apps.
Enable App Check
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
await FirebaseAppCheck.instance.activate(
webProvider: ReCaptchaV3Provider("YOUR_PUBLIC_SITE_KEY"),
);
runApp(MyApp());
}
13. Firebase ML Kit (OCR, Translation, Image Labeling)
Add smart features like text recognition, translation, and image labeling. Uses Google’s machine learning APIs.
Text Recognition (OCR)
Future recognizeText(File imageFile) async {
final InputImage image = InputImage.fromFile(imageFile);
final TextRecognizer textRecognizer = TextRecognizer();
final RecognizedText recognizedText = await textRecognizer.processImage(image);
for (TextBlock block in recognizedText.blocks) {
print("Recognized text: ${block.text}");
}
}
Language Translation
Future translateText(String text) async {
final onDeviceTranslator = OnDeviceTranslator(
sourceLanguage: TranslateLanguage.english,
targetLanguage: TranslateLanguage.spanish,
);
final translatedText = await onDeviceTranslator.translateText(text);
print("Translated text: $translatedText");
}
Image Labeling
Future labelImage(File imageFile) async {
final InputImage inputImage = InputImage.fromFile(imageFile);
final ImageLabeler labeler = GoogleMlKit.vision.imageLabeler();
final List labels = await labeler.processImage(inputImage);
for (ImageLabel label in labels) {
print("Label: ${label.label}, Confidence: ${label.confidence}");
}
labeler.close();
}
14. Firebase Analytics
Analyze user behavior and monitor app engagement. Auto-tracks events and integrates with Google Ads.
Log Custom Events
void logCustomEvent() {
FirebaseAnalytics.instance.logEvent(
name: "purchase",
parameters: {
"item_id": "12345",
"price": 99.99,
},
);
}
15. Firebase Remote Config (Advanced)
Fine-tune app content based on user properties and device conditions. Supports personalized user experiences.
Fetch and Use Remote Config Variables
Future fetchRemoteConfig() async {
final remoteConfig = FirebaseRemoteConfig.instance;
await remoteConfig.fetchAndActivate();
String welcomeMessage = remoteConfig.getString("welcome_message");
print("Remote Config Message: $welcomeMessage");
}
16. Firebase Cloud Functions
Run backend logic serverlessly in response to Firebase events like database updates or authentication changes.
Create a Cloud Function
exports.sendNotification = functions.firestore
.document('messages/{messageId}')
.onCreate((snapshot, context) => {
const message = snapshot.data();
console.log("New message: ", message.text);
return null;
});
17. Firebase Hosting
Host static files, single-page apps, or microservices globally. Offers SSL by default and quick deployments.
Deploy a Web App
firebase init hosting
firebase deploy
18. Firebase Predictions
Use AI-powered analytics to predict user behavior and create targeted experiences.
Fetch Predictions
FirebaseRemoteConfig.instance.fetchAndActivate();
var churnRisk = FirebaseRemoteConfig.instance.getString('churn_risk');
19. Firebase Test Lab
Run automated tests on real devices hosted in the cloud to ensure app quality.
Run a Test Using CLI
gcloud firebase test android run --app app-release.apk
20. Firebase Authentication with Phone OTP
Allow users to sign in using phone number authentication with OTP verification.
Sign in with Phone Number
FirebaseAuth.instance.verifyPhoneNumber(
phoneNumber: '+1234567890',
verificationCompleted: (PhoneAuthCredential credential) {
FirebaseAuth.instance.signInWithCredential(credential);
},
verificationFailed: (FirebaseAuthException e) {
print("Verification failed: ${e.message}");
},
codeSent: (String verificationId, int? resendToken) {
print("Code sent to user.");
},
codeAutoRetrievalTimeout: (String verificationId) {},
);
21. Firebase App Distribution
Distribute pre-release builds to testers easily. Collect feedback before launching to production.
Upload Build for Distribution
firebase appdistribution:distribute app-release.apk --app APP_ID --groups testers
22. Firebase Cloud Firestore Offline Persistence
Enable offline data persistence so users can access data without an internet connection.
Enable Offline Persistence
FirebaseFirestore.instance.settings = Settings(
persistenceEnabled: true,
);
23. Firebase Cloud Firestore Querying & Indexing
Filter, sort, and paginate data with Firestore queries. Use indexes for fast complex searches.
Query Data with Filtering
var query = FirebaseFirestore.instance
.collection('users')
.where('age', isGreaterThan: 18)
.orderBy('name');
24. Firebase Firestore Transactions & Batch Writes
Ensure atomic operations when reading/writing multiple documents.
Firestore Transaction
FirebaseFirestore.instance.runTransaction((transaction) async {
DocumentReference userRef = FirebaseFirestore.instance.collection('users').doc('123');
DocumentSnapshot snapshot = await transaction.get(userRef);
int newBalance = snapshot['balance'] + 100;
transaction.update(userRef, {'balance': newBalance});
});
25. Firebase Realtime Database Offline Mode
Sync and cache data locally when offline, then update once online.
Enable Offline Mode
FirebaseDatabase.instance.setPersistenceEnabled(true);
26. Firebase Authentication with Multi-Factor Authentication (MFA)
Add an extra layer of user security via multiple verification steps. Supports phone and TOTP-based MFA.
Enforce MFA
final multiFactor = FirebaseAuth.instance.currentUser!.multiFactor;
await multiFactor.enroll(
PhoneMultiFactorGenerator.getAssertion(phoneAuthCredential),
);
27. Firebase Cloud Storage Security Rules
Control who can upload, download, and delete files. Define fine-grained access based on user roles.
Secure Storage Rules
rules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
match /user_uploads/{userId}/{fileId} {
allow read, write: if request.auth != null && request.auth.uid == userId;
}
}
}
28. Firebase Firestore Security Rules
Secure Firestore collections with dynamic conditions. Enforces role-based access and user ownership.
Secure Firestore Rules
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /users/{userId} {
allow read, write: if request.auth != null && request.auth.uid == userId;
}
}
}
29. Firebase Cloud Storage File Metadata Handling
Attach metadata like content-type and custom tags to files. Retrieve or update metadata without re-uploading.
Upload File with Metadata
Reference ref = FirebaseStorage.instance.ref("uploads/sample.jpg");
await ref.putFile(file, SettableMetadata(contentType: "image/jpeg"));
30. Firebase Authentication – Custom Claims (Roles & Permissions)
Assign roles like admin, editor, or viewer to users. Use claims for role-based authorization in your app.
Assign Custom Role via Cloud Function
admin.auth().setCustomUserClaims(uid, { role: "admin" });
Check Role in Flutter
final idToken = await FirebaseAuth.instance.currentUser!.getIdTokenResult();
if (idToken.claims?['role'] == 'admin') {
print("User is an admin");
}
31. Firebase Authentication – Anonymous Login
Allow users to use the app without signing up.
Enable Anonymous Login
UserCredential userCredential = await FirebaseAuth.instance.signInAnonymously();
print("User ID: ${userCredential.user?.uid}");
32. Firebase Authentication – Email Verification
Ensure users verify their email before accessing certain features.
Send Verification Email
await FirebaseAuth.instance.currentUser!.sendEmailVerification();
33. Firebase Authentication – Password Reset
Allow users to reset their password via email.
Send Password Reset Email
await FirebaseAuth.instance.sendPasswordResetEmail(email: "user@example.com");
34. Firebase Firestore Change Streams
Listen to real-time updates on Firestore collections. Ideal for live feeds, chats, and collaborative apps.
Listen for Data Changes
FirebaseFirestore.instance.collection("messages").snapshots().listen((snapshot) {
for (var doc in snapshot.docs) {
print("New message: ${doc.data()}");
}
});
35. Firebase Firestore – Subcollections
Organize nested and related data within documents. Supports efficient data grouping and querying.
Access a Subcollection
FirebaseFirestore.instance.collection("users").doc("123").collection("orders").get();
At the End,
And that’s it – we’ve gone through 35 powerful things you can do with Firebase in your Flutter app. From logins to machine learning, this cheat sheet has your back.
I’ll be using this every time I build an app with Firebase, and I hope it helps you too. Just remember — keep it simple, test everything, and don’t forget to take breaks (Firebase isn’t going anywhere!)