Quick Tip: Firestore multiple operations in Flutter

Md Sadab Wasim
Jun 14 · 2 min read

Advance firestore using batch

First of all what firebase documentation says about batch

Cloud Firestore supports atomic operations for reading and writing data. In a set of atomic operations, either all of the operations succeed, or none of them are applied. There are two types of atomic operations in Cloud Firestore:

  • Transactions: a transaction is a set of read and write operations on one or more documents.
  • Batched Writes: a batched write is a set of write operations on one or more documents.

We can use two things to perform multiple operations, and in this article, we’ll cover batch.

Batched writes

If you do not need to read any documents in your operation set (if you need to read document use transaction instead), you can execute multiple write operations as a single batch that contains any combination of set(), update(), or delete() operations. A batch of writes completes atomically and can write to multiple documents.

Write a document

var db= Firestore.instance();//Create a batch
var batch = db.batch();
//And use this batch to write a document.batch.setData(//Give the ref of document.db.collection(’users’).document(’id’),//And the data to add in it.{'status': 'Approved'});

Update a document

//Use the batch to update a documentbatch.updateData(//Give the ref of document.db.collection(’users’).document(’id’),//And the data to update.{'status': 'Rejected'});

Delete a document

//Use the batch to delete a documentbatch.delete(db.collection(’users’).document(’id’));

And just commit the batch, when you want to perform the subscribed actions

batch.commit();
Photo by Vasily Koloda on Unsplash

That’s it, folks.

If you like this tiny little article, just clap for it 👏 👏 👏

Have a great day.

Flutter Community

Articles and Stories from the Flutter Community

Md Sadab Wasim

Written by

Flutter programmer; https://github.com/MDSADABWASIM Develop android apps, Founder of http://Beatless.ml

Flutter Community

Articles and Stories from the Flutter Community