How to Use Firestore with Flutter: Simple Guide
To use
Firestore with Flutter, add the cloud_firestore package to your project, initialize Firebase, then use FirebaseFirestore.instance to read and write data. You can perform operations like adding, updating, and listening to documents in collections with simple Flutter code.Syntax
Here is the basic syntax to use Firestore in Flutter:
FirebaseFirestore.instance: Access the Firestore database.collection('name'): Select a collection.doc('id'): Select a document by ID.set(),add(),update(): Write data.get(): Read data once.snapshots(): Listen to real-time updates.
dart
import 'package:cloud_firestore/cloud_firestore.dart'; final firestore = FirebaseFirestore.instance; // Add a new document firestore.collection('users').add({ 'name': 'Alice', 'age': 25 }); // Read documents once firestore.collection('users').get().then((snapshot) { for (var doc in snapshot.docs) { print(doc.data()); } }); // Listen to real-time updates firestore.collection('users').snapshots().listen((snapshot) { for (var doc in snapshot.docs) { print(doc.data()); } });
Example
This example shows a Flutter app that adds a user to Firestore and listens for real-time updates to display all users.
dart
import 'package:flutter/material.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_core/firebase_core.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp(); runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: UserListPage(), ); } } class UserListPage extends StatelessWidget { final CollectionReference users = FirebaseFirestore.instance.collection('users'); void addUser() { users.add({'name': 'Bob', 'age': 30}); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text('Firestore Users')), body: StreamBuilder<QuerySnapshot>( stream: users.snapshots(), builder: (context, snapshot) { if (!snapshot.hasData) return Center(child: CircularProgressIndicator()); final docs = snapshot.data!.docs; return ListView( children: docs.map((doc) { final data = doc.data() as Map<String, dynamic>; return ListTile( title: Text(data['name'] ?? 'No Name'), subtitle: Text('Age: ${data['age'] ?? 'N/A'}'), ); }).toList(), ); }, ), floatingActionButton: FloatingActionButton( onPressed: addUser, child: Icon(Icons.add), ), ); } }
Output
A Flutter app screen showing a list of users from Firestore updating live; tapping the + button adds a new user named Bob, age 30.
Common Pitfalls
Common mistakes when using Firestore with Flutter include:
- Not initializing Firebase before using Firestore causes runtime errors.
- Forgetting to add
cloud_firestoreandfirebase_corepackages inpubspec.yaml. - Using
get()when you want real-time updates instead ofsnapshots(). - Not handling null or missing fields in documents.
- Ignoring Firestore security rules which can block reads/writes.
dart
/* Wrong: Using Firestore before Firebase initialization */ void main() { runApp(MyApp()); } // Fix: void main() async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp(); runApp(MyApp()); }
Quick Reference
Here is a quick summary of Firestore operations in Flutter:
| Operation | Code Example | Description |
|---|---|---|
| Add document | collection('users').add({'name': 'Anna'}) | Adds a new document with auto ID |
| Set document | doc('id').set({'age': 20}) | Creates or overwrites a document by ID |
| Update document | doc('id').update({'age': 21}) | Updates fields in an existing document |
| Get documents once | collection('users').get() | Fetches documents once |
| Listen to changes | collection('users').snapshots() | Streams real-time updates |
Key Takeaways
Always initialize Firebase before using Firestore in Flutter.
Use cloud_firestore package to interact with Firestore collections and documents.
Use snapshots() for real-time updates and get() for one-time reads.
Handle null values and Firestore security rules carefully.
Add, set, update, and listen to Firestore data with simple Flutter code.