Skip to content

Intermediate · Networking, storage and Firebase · topic 34 of 50 · 35 min

Firebase in Flutter

Explanation

Firebase gives Flutter apps ready backend services. Set it up with the FlutterFire CLI (flutterfire configure), add firebase_core and call Firebase.initializeApp in main after WidgetsFlutterBinding.ensureInitialized(). Use Firebase Auth for email, phone OTP or Google sign-in, Cloud Firestore for a real-time NoSQL database read with snapshots() and StreamBuilder, and always write security rules. Crashlytics and Cloud Messaging add crash reports and push notifications.

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

bash
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_firestore
flutterfire configure registers your Android, iOS and web apps with the Firebase project and writes the config file.
dart
import '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());
}
Initialise Firebase once, before runApp.

Authentication

dart
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: ...)
authStateChanges() is a stream: null when logged out, a User when logged in.

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.

dart
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))]);
      },
    );
The list updates in real time. Queries that combine a filter and an order may need a composite index; Firestore's error message includes a link to create it.

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.

output
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;
    }
  }
}
Users can only create orders for themselves and read or update their own.

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.

Think of it like this: Firebase is like renting space in a well-run office complex: reception (Auth), filing rooms (Firestore), a notice board (Messaging) and a maintenance team reporting problems (Crashlytics) come ready. You still decide who gets which room key (security rules).

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

FlutterFire

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.

dart
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)]);
  },
)
limit(30) keeps reads small and cheap.

Practice (0/3 done)

Task 1 · Question

What must be called before await Firebase.initializeApp(...) in main?

Task 2 · Question

Which Firestore call gives a stream that updates in real time?

Task 3 · Practice

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

Question 1

1.What does flutterfire configure create?

Question 2

2.How is Firestore data organised?

Question 3

3.Why are security rules essential?

Question 4

4.Which service delivers push notifications?

Read more (free)

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

Answer: Crashlytics

Crashlytics collects crash reports.

From Firebase basics

Which Flutter widget rebuilds with the latest value of a stream?Related

Answer: StreamBuilder

StreamBuilder listens and rebuilds.

From Streams

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.

From Core Google Cloud services

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.

From Login with Google, OTP and passkeys

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

  1. This is the last topic of “Networking, storage and Firebase”. The module exam comes next.
  2. Module 8 exam: Networking, storage and Firebase · 13 questions · 25 min, without help. 4 topics of this module still to finish first.
  3. Then the next module, Animations and performance. 50 topics left in the course before the final exam.

← Previous: Local storage