Batch Operations with FlutterFire
Sometimes you need to make batch operations like you want to add a list in a single go. Adding a list in a loop with multiple backend calls is not a good way to do it. Luckily firestore allows you to make batch operations.
As Firebase documentation says you execute multiple write operations as a single batch that can contain any combination of set
, update
, or delete
operations.
We will take an example of List of Cities to understand it better.
class City {
String id;
String name;City({this.name}) :id=null;City.fromSnapshot(DocumentSnapshot doc) : assert(doc != null),
id = doc.id,
name = doc.data()[‘name’];
}
First, create a new batch instance via the batch
method, then perform the operations on the batch, and then commit it once ready.
Adding in batch
void addBatchCities() {
final CitiesRef = FirebaseFirestore.instance.collection(COLLECTION_CITIES);
WriteBatch batch = FirebaseFirestore.instance.batch();
final cities = getCities();
for (City city in cities) {
final newCityItem = CitiesRef.doc();
batch.set(newCityItem, {
'name': city.name,
'createdAt': DateTime.now().millisecondsSinceEpoch
});
}
batch.commit();
}
Updating in batch
Future<void> updateBatchCities() {
final CitiesRef = FirebaseFirestore.instance.collection(COLLECTION_CITIES);
WriteBatch batch = FirebaseFirestore.instance.batch();
return CitiesRef.get().then((querySnapshot) {
var count = 0;
querySnapshot.docs.forEach((document) {
batch.update(document.reference, {'name': 'City${count++}'});
});
return batch.commit();
});
}
Deleting in batch
Future<void> deleteBatchCities() {
final CitiesRef = FirebaseFirestore.instance.collection(COLLECTION_CITIES);
WriteBatch batch = FirebaseFirestore.instance.batch(); return CitiesRef.get().then((querySnapshot) {
querySnapshot.docs.forEach((document) {
batch.delete(document.reference);
}); return batch.commit();
});
}
For Complete code:
https://github.com/BilalSiddiqui/Firestore-Batch-Operations
Thanks for reading. Just clap if you like it.
Follow me for more Firebase, Flutter and Android articles.