What is Firestore?
Cloud Firestore is a NoSQL cloud database. Data is stored in documents (like JSON objects) inside collections (like folders). The best part: changes appear on all devices in real time.
| Concept | Meaning | Example |
| Collection | A group of documents | todos |
| Document | One record with fields | todos/abc123 |
| Field | A value inside a document | title: 'Buy milk' |
Setup
Complete the Firebase setup from the previous lesson, then enable Firestore Database in the Firebase console (start in test mode while learning) and add the package.
bash
flutter pub add cloud_firestore
Create (Add a Document)
dart
import 'package:cloud_firestore/cloud_firestore.dart';
final todos = FirebaseFirestore.instance.collection('todos');
Future<void> addTodo(String title, String uid) async {
await todos.add({
'title': title,
'done': false,
'uid': uid,
'createdAt': FieldValue.serverTimestamp(),
});
}
Read Once
dart
final snapshot = await todos.get();
for (final doc in snapshot.docs) {
print('${doc.id} => ${doc.data()}');
}
Read in Real Time with StreamBuilder
dart
StreamBuilder<QuerySnapshot<Map<String, dynamic>>>(
stream: todos.where('uid', isEqualTo: uid).orderBy('createdAt', descending: true).snapshots(),
builder: (context, snapshot) {
if (snapshot.hasError) return Text('Error: ${snapshot.error}');
if (!snapshot.hasData) return const Center(child: CircularProgressIndicator());
final docs = snapshot.data!.docs;
if (docs.isEmpty) return const Center(child: Text('No todos yet'));
return ListView.builder(
itemCount: docs.length,
itemBuilder: (context, i) {
final data = docs[i].data();
return CheckboxListTile(
title: Text(data['title'] as String),
value: data['done'] as bool,
onChanged: (v) => docs[i].reference.update({'done': v}),
);
},
);
},
)
Magic moment: Open the app on two devices. Add a todo on one, and it appears on the other within a moment, with no refresh code.
Update and Delete
dart
await todos.doc(docId).update({'done': true});
await todos.doc(docId).set({'title': 'New', 'done': false}); // replace or create
await todos.doc(docId).delete();
Queries
dart
todos.where('done', isEqualTo: false)
todos.where('priority', isGreaterThan: 2)
todos.orderBy('createdAt', descending: true).limit(10)
todos.where('tags', arrayContains: 'work')
Some queries need an index. If Firestore needs one, the error message contains a link that creates it with one click.
Use Typed Models
dart
final typed = FirebaseFirestore.instance.collection('todos').withConverter<Todo>(
fromFirestore: (snap, _) => Todo.fromJson({...snap.data()!, 'id': snap.id}),
toFirestore: (todo, _) => todo.toJson(),
);
Security Rules (Very Important)
Test mode lets everyone read and write your database. Before you publish the app, restrict access in the Firebase console under Firestore > Rules.
javascript
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /todos/{todoId} {
allow read, write: if request.auth != null
&& request.auth.uid == resource.data.uid;
allow create: if request.auth != null
&& request.auth.uid == request.resource.data.uid;
}
}
}
These rules allow only the owner of a todo to read, change or delete it, and logged-in users to create their own.
Cost tip: Firestore bills per read and write. Use limit(), avoid reading whole collections on every screen and keep your queries specific.
Conclusion
Firestore gives you a real-time cloud database with almost no backend work. Use snapshots for live UI and never leave test-mode rules in a published app.
Quick Summary: Use collection and doc references to add, get, update and delete, snapshots with StreamBuilder for live data and security rules for protection.