Intermediate · Networking, storage and Firebase · topic 34 of 50 · 35 min
Firebase in Flutter
Explanation
Why Firebase?
Building your own server for login, a database and notifications takes time and backend skills. Firebase, by Google, provides these as managed services with official Flutter plugins (the FlutterFire project). Many startups and student projects use it to launch quickly; a separate backend can be added later if needed.
Setup with the FlutterFire CLI
npm install -g firebase-tools # the Firebase CLI (one way to install it)
firebase login
dart pub global activate flutterfire_cli
flutterfire configure # choose a project and platforms; creates lib/firebase_options.dart
flutter pub add firebase_core firebase_auth cloud_firestoreimport 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'firebase_options.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized(); // needed before async work in main
await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
runApp(const MyApp());
}Authentication
final auth = FirebaseAuth.instance;
Future<void> signUp(String email, String password) =>
auth.createUserWithEmailAndPassword(email: email, password: password);
Future<void> signIn(String email, String password) =>
auth.signInWithEmailAndPassword(email: email, password: password);
// Listen to login state anywhere:
// StreamBuilder<User?>(stream: auth.authStateChanges(), builder: ...)Firebase Auth also supports phone number sign-in with OTP (popular in India), Google sign-in and others. Phone auth sends real SMS, which has costs at scale and needs extra setup on each platform; use the test phone numbers feature during development.
Cloud Firestore
Firestore is a NoSQL document database: data is stored in documents (like JSON objects) grouped into collections. Reads can be one-time (get) or live (snapshots), which return a stream that updates the moment data changes, ideal for chat, order tracking and live dashboards.
final orders = FirebaseFirestore.instance.collection('orders');
Future<void> placeOrder(String uid, String item) => orders.add({
'uid': uid,
'item': item,
'status': 'placed',
'createdAt': FieldValue.serverTimestamp(),
});
Widget myOrders(String uid) => StreamBuilder<QuerySnapshot<Map<String, dynamic>>>(
stream: orders.where('uid', isEqualTo: uid).orderBy('createdAt', descending: true).snapshots(),
builder: (context, snap) {
if (!snap.hasData) return const Center(child: CircularProgressIndicator());
final docs = snap.data!.docs;
return ListView(children: [for (final d in docs) ListTile(title: Text(d['item'] as String), subtitle: Text(d['status'] as String))]);
},
);Security rules: essential
Your app talks to Firestore directly, so the database must decide who may read and write what. Security rules, written in the Firebase console, do this on Google's servers. Test mode allows open access for a short time; before real users arrive, write rules such as "a user may only read and write their own orders". Leaving rules open has exposed many apps' data.
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /orders/{orderId} {
allow read, update: if request.auth != null && resource.data.uid == request.auth.uid;
allow create: if request.auth != null && request.resource.data.uid == request.auth.uid;
}
}
}More services
- Crashlytics: crash reports with stack traces from real users.
- Cloud Messaging (FCM): push notifications, with firebase_messaging.
- Cloud Storage: user uploads like profile photos.
- Analytics and Remote Config: usage data and server-controlled settings.
Pricing: Firebase has a free Spark plan with limits and a pay-as-you-go Blaze plan; some features need Blaze. Read the current pricing page, set budget alerts, and avoid queries that read whole collections.
Common mistakes
- Forgetting WidgetsFlutterBinding.ensureInitialized() before Firebase.initializeApp.
- Shipping with test-mode or open security rules.
- Reading entire collections on every screen open: slow and costly. Filter and limit queries.
- Not declaring Firebase's data collection in the Play Store Data safety form and App Store privacy details.
Need help?
Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.
Try:
Watch the lesson
Firebase in Flutter · 1/6
Firebase gives apps ready backend services: login, a real time database, files, notifications and crash reports.
Prefer a video by a teacher? Find free videos on “flutterfire setup firebase auth cloud firestore flutter tutorial security rules” on YouTube ↗
In real life: A housing society notice board
A housing society app lets residents log in with their phone number (Firebase Auth), see notices that appear instantly when the committee posts them (Firestore snapshots with StreamBuilder), and get a push notification for urgent ones like water supply cuts (FCM). Security rules allow residents to read notices but only committee members to write them.
StreamBuilder<QuerySnapshot<Map<String, dynamic>>>(
stream: FirebaseFirestore.instance.collection('notices').orderBy('postedAt', descending: true).limit(30).snapshots(),
builder: (context, snap) {
if (snap.hasError) return const Text('Could not load notices');
if (!snap.hasData) return const CircularProgressIndicator();
return Column(children: [for (final d in snap.data!.docs) Text(d['title'] as String)]);
},
)Practice (0/3 done)
What must be called before await Firebase.initializeApp(...) in main?
Which Firestore call gives a stream that updates in real time?
Create a Firebase project, run flutterfire configure, and build: email sign-up and login screens, a StreamBuilder on authStateChanges that shows the login screen or a home screen, and a "my notes" list stored under users/{uid}/notes with live updates. Write rules so each user can only access their own notes.
Quick quiz
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- JSON modelsNetworking, storage and Firebase · same module
- HTTP requests and FutureBuilderNetworking, storage and Firebase · same module
- Firebase basicsKotlin and Android App Development · Publishing on the Play Store and Firebase
- Core Google Cloud servicesCloud Computing (AWS, Azure, Google Cloud) · Google Cloud and comparing the clouds
- Login with Google, OTP and passkeysBackend Development · Authentication and authorization
- Flutter on the web and desktopPublishing to the stores and the web
Questions people ask about this
Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.
What does flutterfire configure create?
Answer: lib/firebase_options.dart with your Firebase app configuration
It connects your app to the Firebase project.
How is Firestore data organised?
Answer: Collections of documents
Firestore is a document database.
Why are security rules essential?
Answer: Apps access the database directly; rules decide who may read and write
Never leave rules open.
Which service delivers push notifications?
Answer: Cloud Messaging (FCM)
Use firebase_messaging in Flutter.
Which Firebase service reports crashes from users' devices?Related
Which Flutter widget rebuilds with the latest value of a stream?Related
How is a VPC network scoped in Google Cloud?Related
Answer: Global, with regional subnets
Google Cloud VPC networks are global resources; each subnet lives in one region.
Why limit OTP attempts to about 5?Related
Answer: So nobody can try all 1,000,000 codes
Without a limit, an attacker could guess codes until one works.
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.
Next steps
- This is the last topic of “Networking, storage and Firebase”. The module exam comes next.
- Module 8 exam: Networking, storage and Firebase · 13 questions · 25 min, without help. 4 topics of this module still to finish first.
- Then the next module, Animations and performance. 50 topics left in the course before the final exam.