Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Flutter & Firestore: How to check the commit() of the batch is a success or not?

The basic code is:

Future batchSet() async {
  WriteBatch batch = FirebaseFirestore.instance.batch();
  for (var value in dataList) {
    batch.set(FirebaseFirestore.instance.collection('batch').doc(), {
      'createAt': FieldValue.serverTimestamp(),
      'data': value,
    });
  }
  await batch.commit();
}

How to check the result when committed?

I tried await batch.commit().then((value) {}); but the value type is void, can’t do anything with value.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Or I just use this:

try {
    await batch.commit();
  } catch (e) {}

Is this work fine if I use try/catch with only the commit()?

>Solution :

A promise can end in two ways:

  • It can either resolve, in which case its then clause is executed with the result of the call passed as a parameter. In the case of a batch.commit there is indeed no result.
  • Or it can be rejected, in which case its catch clause is executed with an error object to indicate what went wrong.

Since you’re using async/await, the then clause is essentially the code in the same code-block right after the awaited call. To catch a rejection, use a try-catch block as you did in your last snippet. The e parameter has information on why the promise/commit failed.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading