runTransaction<T> method

Future<T> runTransaction<T>(
  1. TransactionHandler<T> updateFunction, {
  2. Duration timeout = const Duration(seconds: 30),
  3. int maxAttempts = 5,
  4. bool readOnly = false,
  5. Timestamp? readTime,
})

Runs updateFunction in a transaction and commits its writes atomically; completes with the value it returns.

Transactions are optimistic: Transaction.get reads the current version of a document from the backend, and the commit fails if a document that was read changed in the meantime. Then updateFunction runs again, up to maxAttempts times (5 by default), after which the returned future fails with the last error. So updateFunction can run more than once: it must not have side effects of its own, and it must do all its reads before its writes. If updateFunction throws, nothing is committed and the future fails with that error.

The reads of a transaction go to the backend, never to the cache, so a transaction fails when the backend cannot be reached. Writes made with Transaction are only sent at the commit and are not visible locally before.

After timeout (30 seconds by default, as in FlutterFire) the returned future fails with a FirestoreException with FirestoreErrorCode.deadlineExceeded and no new attempt starts. The attempt that runs at that moment is not cancelled: if it was committing, its writes may still take effect.

maxAttempts must be at least 1. With readOnly it is a read-only transaction, which reads a consistent snapshot of the database and can also run queries with Transaction.getQuery and aggregations with Transaction.getAggregate. The JS and Android client SDKs have no read-only transactions.

A commit whose answer is lost on the network can be applied twice, as in the other SDKs: make transactions that must not run twice idempotent.

There is no limit on the number of writes in a transaction, but its commit request must not exceed the maximum API request size of 10 MiB, and a single document takes at most 500 field transforms (such as FieldValue.serverTimestamp or FieldValue.increment).

final DocumentReference<Map<String, Object?>> sf = firestore.doc(
  'cities/SF',
);
final int newPopulation = await firestore.runTransaction((
  Transaction transaction,
) async {
  final DocumentSnapshot<Map<String, Object?>> snapshot = await transaction
      .get(sf);
  final int population = snapshot.get('population') as int? ?? 0;
  transaction.update(sf, {'population': population + 1});
  return population + 1;
});
print(newPopulation);

Implementation

Future<T> runTransaction<T>(
  TransactionHandler<T> updateFunction, {
  Duration timeout = const Duration(seconds: 30),
  int maxAttempts = 5,
  bool readOnly = false,
  Timestamp? readTime,
}) {
  if (timeout <= Duration.zero) {
    throw ArgumentError.value(timeout, 'timeout', 'must be positive');
  }
  final TransactionOptions options = TransactionOptions(
    maxAttempts: maxAttempts,
    readOnly: readOnly,
    readTime: readTime,
  );
  bool timedOut = false;
  // We wrap the function they provide in order to
  // 1. Use internal implementation classes for Transaction,
  // 2. Convert exceptions they throw into Futures, and
  // 3. Run the user callback on the user queue.
  Future<T> wrappedUpdateFunction(core.Transaction internalTransaction) {
    if (timedOut) {
      // No new attempt after the timeout. An error that is not a FirestoreException is not retried.
      throw const TransactionTimedOut();
    }
    return updateFunction(
      TransactionInternal.create(internalTransaction, this),
    );
  }

  return client
      .transaction(
        wrappedUpdateFunction,
        options.maxAttempts,
        readOnly: options.readOnly,
        readTime: options.readTime == null
            ? null
            : SnapshotVersion(options.readTime!),
      )
      .timeout(
        timeout,
        onTimeout: () {
          timedOut = true;
          throw FirestoreException(
            errorCode: FirestoreErrorCode.deadlineExceeded,
            message:
                'The transaction did not complete within $timeout. An attempt that was committing may still '
                'take effect.',
          );
        },
      );
}