Skip to content
Tutorials Center
My learning

Topics

Lesson 48 of 73 ยท Platform integration

Firebase: Auth, Firestore and Cloud Messaging

Connect Flutter to Firebase with FlutterFire: sign-in flows, Firestore reads, writes and queries, security rules and push notifications with Cloud Messaging.

Most apps need a backend: accounts, a database and a way to reach users when the app is closed. Firebase bundles those as managed services, and FlutterFire is the set of Flutter packages that talks to them. You can ship a working multi-user app without running a single server.

This lesson covers setup, the three services you will use most (Authentication, Cloud Firestore and Cloud Messaging), and the part that decides whether your data is safe: security rules. Firebase is a hosted service, so everything here is read-only; the live stand-ins model the ideas that matter, namely how a document query and a rule check behave.

Real vs stand-in. The Dart, JSON and rules snippets are real and read-only. The site has no Firebase project, so the JavaScript stand-ins are small in-memory models of a Firestore collection and a security-rule check. Real Firestore adds indexes, offline persistence, network latency and limits that the stand-ins do not.

Three services

Authentication Who is this user?
Firestore Documents in collections, live.
Cloud Messaging Push to closed apps.
1 / 2

Setup

Install the Firebase CLI and the FlutterFire CLI, log in, and run the configuration command inside your Flutter project:

Terminal
dart pub global activate flutterfire_cli
flutterfire configure
flutter pub add firebase_core firebase_auth cloud_firestore firebase_messaging

flutterfire configure registers each platform (Android, iOS, web, ...) in your Firebase project and writes lib/firebase_options.dart. These identifiers are not secrets: they name your project, and protection comes from security rules, not from hiding them. Then initialize before the app starts:

DART
Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
  runApp(const MyApp());
}

ensureInitialized() is needed because main awaits plugin code (platform channels, see Platform channels) before runApp.

Authentication

Enable sign-in methods in the console (email/password, Google, Apple, phone...). Then:

DART
final auth = FirebaseAuth.instance;

Future<void> register(String email, String password) async {
  try {
    await auth.createUserWithEmailAndPassword(email: email, password: password);
  } on FirebaseAuthException catch (e) {
    switch (e.code) {
      case 'email-already-in-use': throw 'That email already has an account.';
      case 'weak-password': throw 'Choose a longer password.';
      default: throw 'Sign-up failed (${e.code}).';
    }
  }
}

Future<void> signIn(String email, String password) =>
    auth.signInWithEmailAndPassword(email: email, password: password);

Future<void> signOut() => auth.signOut();

The key idea is not the call but the auth state stream. Rather than remembering whether you signed in, let the UI follow the stream; it fires at start-up (restoring the saved session), on sign-in and on sign-out:

DART
class AuthGate extends StatelessWidget {
  const AuthGate({super.key});

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<User?>(
      stream: FirebaseAuth.instance.authStateChanges(),
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return const Scaffold(body: Center(child: CircularProgressIndicator()));
        }
        return snapshot.hasData ? const HomePage() : const LoginPage();
      },
    );
  }
}

Social providers (Google, Apple) use the same stream; their sign-in packages return a credential that you pass to signInWithCredential. Apple requires "Sign in with Apple" on iOS if you offer other third-party logins. The user object has a uid, a stable id you will use as a key in your data. See Forms and validation for the login form itself and StreamBuilder for the pattern above.

Cloud Firestore

Firestore is a document database. Data lives in documents (maps of fields), grouped in collections. Documents can contain subcollections: users/{uid}/notes/{noteId}.

DART
final notes = FirebaseFirestore.instance.collection('notes');

// Create (auto id) and set (known id)
final ref = await notes.add({
  'ownerId': uid,
  'title': 'Buy milk',
  'done': false,
  'createdAt': FieldValue.serverTimestamp(),
});
await notes.doc('welcome').set({'title': 'Hello'}, SetOptions(merge: true));

// Update some fields, delete
await ref.update({'done': true});
await ref.delete();

// One-time read
final snap = await notes.doc('welcome').get();
if (snap.exists) print(snap.data());

Queries

A query filters, orders and limits one collection:

DART
final query = notes
    .where('ownerId', isEqualTo: uid)
    .where('done', isEqualTo: false)
    .orderBy('createdAt', descending: true)
    .limit(20);

final result = await query.get();
for (final doc in result.docs) {
  print('${doc.id}: ${doc['title']}');
}

Firestore only runs queries it can answer from an index. Single-field indexes are automatic; a query that combines a filter and an order on different fields needs a composite index, and the error message in the debug console includes a link that creates it. There is no join and no free-text search: shape the data for your queries (duplicate a field if you must) instead of asking the database to be relational.

Live data with snapshots

snapshots() returns a stream that emits again whenever the matching data changes, on any device. This pairs naturally with StreamBuilder:

DART
StreamBuilder<QuerySnapshot<Map<String, dynamic>>>(
  stream: query.snapshots(),
  builder: (context, snapshot) {
    if (snapshot.hasError) return Text('Error: ${snapshot.error}');
    if (!snapshot.hasData) return const CircularProgressIndicator();
    final docs = snapshot.data!.docs;
    return ListView.builder(
      itemCount: docs.length,
      itemBuilder: (_, i) => CheckboxListTile(
        title: Text(docs[i]['title'] as String),
        value: docs[i]['done'] as bool,
        onChanged: (v) => docs[i].reference.update({'done': v}),
      ),
    );
  },
)

Firestore also keeps a local cache, so reads work offline on mobile and writes sync later. Create the stream once (in a repository or initState), not in build, to avoid re-subscribing on every rebuild. In a typed app, use withConverter or your own model classes between the map and the UI (HTTP and JSON shows the model pattern).

Stand-in: documents and queries

JS A tiny in-memory Firestore collection

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The query result updates by itself when a matching document is added or leaves the filter. That is what snapshots() gives your UI: you write a query once and the list follows.

Security rules

A Flutter app runs on the user's device, so a user (or an attacker using your project id) can send any request to Firestore. Security rules run on Google's servers and decide which requests are allowed. Without proper rules, your data is open or closed to everyone, depending on the mode you chose. Rules are the real backend logic; client checks are only for user experience.

TEXT
rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {

    match /notes/{noteId} {
      allow read: if request.auth != null && resource.data.ownerId == request.auth.uid;
      allow create: if request.auth != null
                    && request.resource.data.ownerId == request.auth.uid
                    && request.resource.data.title is string
                    && request.resource.data.title.size() <= 200;
      allow update, delete: if request.auth != null && resource.data.ownerId == request.auth.uid;
    }
  }
}

Note that queries must be consistent with the rule: a rule that says "only read your own notes" means the query must include where('ownerId', isEqualTo: uid); Firestore rejects a query that could return other people's data rather than filtering it. Test rules with the Firebase Emulator Suite and its rules unit tests before shipping.

JS Stand-in: checking a request against a rule

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Cloud Messaging (push)

FCM delivers messages to devices that may be closed. The Flutter side is small; the sending side is a server or Cloud Function using the token.

DART
final messaging = FirebaseMessaging.instance;

Future<void> setUpPush() async {
  final settings = await messaging.requestPermission();   // iOS and Android 13+
  if (settings.authorizationStatus == AuthorizationStatus.denied) return;

  final token = await messaging.getToken();               // send this to your backend
  messaging.onTokenRefresh.listen(saveTokenOnServer);

  FirebaseMessaging.onMessage.listen((m) {
    // app is open: show your own banner
  });
  FirebaseMessaging.onMessageOpenedApp.listen((m) {
    // user tapped a notification while the app was in the background
  });
  final initial = await messaging.getInitialMessage();     // opened from terminated state
}

@pragma('vm:entry-point')
Future<void> firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  await Firebase.initializeApp();   // runs in its own isolate
}

Register the background handler with FirebaseMessaging.onBackgroundMessage(...) in main. A notification message is displayed by the system; a data message goes to your code only. Use topics (messaging.subscribeToTopic('news')) for broadcasts. The permission steps and iOS APNs key are described in Camera, Location, Permissions and Notifications.

Common mistakes

  • Leaving test-mode rules (allow read, write: if true) in production.
  • Trusting the client: validating only in Dart does not protect the data.
  • Re-creating a stream in build, which re-subscribes and re-reads on every rebuild.
  • Reading whole collections with no limit: you pay per document read.
  • Storing per-user data under a shared id instead of the user's uid.
  • Forgetting the background handler is a top-level function, not a method.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why should the UI listen to authStateChanges() instead of remembering a login flag?

    The stream is the single source of truth; the screen switches whenever it emits.
  2. 2. Your rule allows reading only notes whose ownerId equals the user's uid. Which query is accepted?

    Firestore checks that the query itself can only return allowed documents; it does not silently filter.
  3. 3. Are the values in firebase_options.dart secret?

    They ship inside every app anyway. Rules and authentication are the protection.
  4. 4. What does snapshots() give you compared with get()?

    get() reads once, snapshots() subscribes to changes.
  5. 5. A user taps a push notification while the app is fully closed. Where do you read that message?

    getInitialMessage returns the message that launched the app from the terminated state.

Summary

  • flutterfire configure and Firebase.initializeApp connect the app; the generated options are not secrets.
  • Authentication: sign in with a method, then drive the UI from authStateChanges() and use uid as the key.
  • Firestore stores documents in collections; queries need indexes, and snapshots() streams live results.
  • Security rules run on the server and are the real access control; test them with the emulator.
  • FCM needs permission, a device token and handlers for foreground, background and terminated states.

Next: Flutter on Web and Desktop