How to Use Firestore with Flutter: Simple Guide
To use
Firestore with Flutter, add the cloud_firestore package to your project, initialize Firebase, and then use Firestore methods to read and write data. You interact with Firestore collections and documents using Flutter widgets and async calls.Syntax
First, add the cloud_firestore package to your pubspec.yaml. Then import it in your Dart code. Use FirebaseFirestore.instance to access Firestore. Collections and documents are accessed with collection('name') and doc('id'). Use get() to read and set() or add() to write data.
dart
import 'package:cloud_firestore/cloud_firestore.dart'; final firestore = FirebaseFirestore.instance; // Access a collection CollectionReference users = firestore.collection('users'); // Read a document Future<DocumentSnapshot> getUser(String id) { return users.doc(id).get(); } // Write data Future<void> addUser(String id, Map<String, dynamic> data) { return users.doc(id).set(data); }
Example
This example shows a Flutter app that connects to Firestore, adds a user document, and reads it back to display the user's name.
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 { final CollectionReference users = FirebaseFirestore.instance.collection('users'); Future<void> addUser() async { await users.doc('user1').set({'name': 'Alice', 'age': 25}); } Future<String> getUserName() async { DocumentSnapshot doc = await users.doc('user1').get(); return doc.exists ? doc['name'] : 'No user'; } @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar(title: Text('Firestore with Flutter')), body: Center( child: FutureBuilder<String>( future: () async { await addUser(); return await getUserName(); }(), builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.waiting) { return CircularProgressIndicator(); } else if (snapshot.hasError) { return Text('Error: ${snapshot.error}'); } else { return Text('User name: ${snapshot.data}'); } }, ), ), ), ); } }
Output
User name: Alice
Common Pitfalls
- Not initializing Firebase before using Firestore causes runtime errors.
- Forgetting to add
cloud_firestoretopubspec.yamlor not runningflutter pub get. - Trying to read documents without awaiting async calls leads to empty or null data.
- Incorrect Firestore rules can block reads/writes; always check your Firebase console rules.
dart
/* Wrong: Not awaiting async call */ var doc = FirebaseFirestore.instance.collection('users').doc('user1').get(); print(doc.data()); // Error: data() called on Future /* Right: Await the Future */ var doc = await FirebaseFirestore.instance.collection('users').doc('user1').get(); print(doc.data());
Quick Reference
Here is a quick summary of common Firestore operations in Flutter:
| Operation | Code Example |
|---|---|
| Get collection | FirebaseFirestore.instance.collection('users') |
| Get document | collection.doc('docId').get() |
| Add document | collection.add({'field': 'value'}) |
| Set document | collection.doc('docId').set({'field': 'value'}) |
| Update document | collection.doc('docId').update({'field': 'newValue'}) |
| Delete document | collection.doc('docId').delete() |
Key Takeaways
Always initialize Firebase before using Firestore in Flutter apps.
Use async/await to handle Firestore data reads and writes properly.
Add the cloud_firestore package and import it to access Firestore features.
Check Firestore security rules to avoid permission errors.
Use CollectionReference and DocumentReference to organize Firestore data.