commit method

Future<void> commit()

Commits all the writes of this batch as a single atomic unit.

The writes are applied to the local cache at once: listeners see them right away, with hasPendingWrites set in their metadata. The returned future completes when the backend has acknowledged the batch.

While the client is offline the future does not complete: the batch stays queued and is sent when the client is online again (with a persistent cache, also after the app restarts). Do not wait for the future if your app must keep going offline.

If the backend rejects the batch, for example with FirestoreErrorCode.permissionDenied from the security rules or FirestoreErrorCode.notFound for an update of a missing document, the future fails with that FirestoreException and the writes are removed from the local cache again. Errors that a retry can fix (such as FirestoreErrorCode.unavailable) are retried by the client and are not reported.

final WriteBatch batch = firestore.batch()
  ..set(firestore.doc('cities/SF'), <String, Object?>{'name': 'SF'});
await batch.commit();

A batch can be committed once; afterwards every call on it throws a StateError. If the FirebaseFirestore instance was terminated, the future fails with FirestoreErrorCode.failedPrecondition; an empty batch completes at once without any check.

Implementation

Future<void> commit() async {
  _verifyNotCommitted();
  _committed = true;
  if (_mutations.isNotEmpty) {
    await _firestore.client.write(_mutations);
  }
}