Cloud Firestore lets your app save, read, update, and delete data in the cloud. This helps your app share data with users instantly and keep it safe.
Cloud Firestore CRUD in Flutter
final docRef = FirebaseFirestore.instance.collection('collectionName').doc('docId'); // Create or update await docRef.set({'field': 'value'}); // Read final snapshot = await docRef.get(); final data = snapshot.data(); // Update await docRef.update({'field': 'newValue'}); // Delete await docRef.delete();
set() creates or replaces a document.
update() changes only specified fields.
await FirebaseFirestore.instance.collection('users').doc('user1').set({'name': 'Alice', 'age': 25});
final snapshot = await FirebaseFirestore.instance.collection('users').doc('user1').get(); print(snapshot.data());
await FirebaseFirestore.instance.collection('users').doc('user1').update({'age': 26});
await FirebaseFirestore.instance.collection('users').doc('user1').delete();
This Flutter app shows buttons to add, update, get, and delete a user document in Firestore. The text updates to show the current action or data.
import 'package:flutter/material.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: FirestoreDemo(), ); } } class FirestoreDemo extends StatefulWidget { @override _FirestoreDemoState createState() => _FirestoreDemoState(); } class _FirestoreDemoState extends State<FirestoreDemo> { final CollectionReference users = FirebaseFirestore.instance.collection('users'); Future<void> addUser() async { await users.doc('user1').set({'name': 'Alice', 'age': 25}); } Future<void> updateUser() async { await users.doc('user1').update({'age': 26}); } Future<void> deleteUser() async { await users.doc('user1').delete(); } Future<Map<String, dynamic>?> getUser() async { final doc = await users.doc('user1').get(); return doc.exists ? doc.data() as Map<String, dynamic>? : null; } String displayText = 'No data'; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text('Firestore CRUD Demo')), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text(displayText), SizedBox(height: 20), ElevatedButton( onPressed: () async { await addUser(); setState(() { displayText = 'User added'; }); }, child: Text('Add User'), ), ElevatedButton( onPressed: () async { await updateUser(); setState(() { displayText = 'User updated'; }); }, child: Text('Update User'), ), ElevatedButton( onPressed: () async { final data = await getUser(); setState(() { displayText = data != null ? 'Name: ${data['name']}, Age: ${data['age']}' : 'User not found'; }); }, child: Text('Get User'), ), ElevatedButton( onPressed: () async { await deleteUser(); setState(() { displayText = 'User deleted'; }); }, child: Text('Delete User'), ), ], ), ), ); } }
Make sure to initialize Firebase in your app before using Firestore.
Use set() to create or replace documents, and update() to change only some fields.
Always check if a document exists before reading its data to avoid errors.
Cloud Firestore stores app data in collections and documents.
CRUD means Create, Read, Update, and Delete data.
Flutter uses FirebaseFirestore.instance to access Firestore and perform these actions.
Practice
What does CRUD stand for in Cloud Firestore operations?
Solution
Step 1: Understand CRUD acronym meaning
CRUD is a common term in databases meaning the four basic operations on data.Step 2: Match each letter to the correct operation
C = Create, R = Read, U = Update, D = Delete are the standard meanings.Final Answer:
Create, Read, Update, Delete -> Option CQuick Check:
CRUD = Create, Read, Update, Delete [OK]
- Confusing CRUD letters with unrelated words
- Mixing up 'Remove' with 'Delete'
- Thinking CRUD includes 'Download'
Which Flutter code snippet correctly adds a new document to a Firestore collection named users?
FirebaseFirestore.instance.collection('users').____({'name': 'Alice'});Solution
Step 1: Identify method to add new document
Theaddmethod creates a new document with given data in the collection.Step 2: Confirm other methods' purposes
updatemodifies existing documents,deleteremoves documents,getreads data.Final Answer:
add -> Option BQuick Check:
Adding new document uses add() [OK]
- Using update() to add new documents
- Confusing get() with add()
- Trying to delete() when adding data
What will be the output of this Flutter Firestore code snippet?
var doc = await FirebaseFirestore.instance.collection('tasks').doc('task1').get();
print(doc.exists);Assuming the document task1 exists in the tasks collection.
Solution
Step 1: Understand doc.get() behavior
Theget()method fetches the document snapshot from Firestore.Step 2: Check the
If the document exists,existspropertydoc.existsreturns true; otherwise false.Final Answer:
true -> Option AQuick Check:
Document exists property = true [OK]
- Assuming doc.exists returns document data
- Expecting false even if document exists
- Not awaiting the get() call
Identify the error in this Flutter Firestore update code:
FirebaseFirestore.instance.collection('users').doc('user1').update({'age': 30});Assuming the document user1 does not exist.
Solution
Step 1: Understand update() behavior on missing document
Theupdate()method requires the document to exist; otherwise, it throws an error.Step 2: Confirm no syntax errors
The syntax is correct, so error is due to missing document.Final Answer:
Throws an error because document does not exist -> Option DQuick Check:
update() fails if document missing [OK]
- Thinking update() creates new documents
- Confusing update() with set()
- Ignoring async/await for update()
You want to delete a Firestore document only if it exists to avoid errors. Which Flutter code snippet correctly does this?
var docRef = FirebaseFirestore.instance.collection('orders').doc('order1');
// What code to safely delete?Solution
Step 1: Check document existence before deleting
Useget()to fetch the document snapshot and checkexists.Step 2: Call delete() only if document exists
This avoids errors from deleting non-existing documents.Final Answer:
docRef.get().then((doc) { if (doc.exists) docRef.delete(); }); -> Option AQuick Check:
Check exists before delete to avoid errors [OK]
- Calling delete() without checking existence
- Using update() to delete documents
- Setting document to null instead of deleting
Ready to prove it?
Pass the test and this pattern moves unknown
