runInTransaction method

Future<void> runInTransaction(
  1. {@required Reach reach,
  2. @required Duration timeout,
  3. @required Future<void> callback(
    1. Transaction transaction

Runs a transaction.

Parameter reach defines reach of commit. Value null means that the adapter can choose any reach.

Parameter timeout defines timeout for the transaction. Null value means that the database adapter should decide itself. Database adapters should cancel the transaction if the timeout is reached before the transaction has been committed. Timer starts from runInTransaction invocation. However, database adapters are free to ignore the parameter.

Parameter callback defines the function that performs changes. It may be invoked any number of times during the transaction. The function receives a Transaction that enables transactional reading and writing.

Database adapter will throw DatabaseException.transactionUnsupported if it doesn't support transactions.

Transferring money between two bank accounts would look something like:

Future<void> transferMoney(String from, String to, double amount) async {
  final fromDocument = database.collection('bank_account').document(from);
  final toDocument = database.collection('bank_account').document(to);
  await database.runInTransaction(
    timeout: Duration(seconds:3),
    callback: (transaction) async {
      // Read documents
      final fromSnapshot = await transaction.get(fromDocument);
      final toSnapshot = await transaction.get(toDocument);

      // Patch documents
      await transaction.patch(fromDocument, {
        'amount':['amount'] - amount,
      await transaction.patch(toDocument, {
        'amount':['amount'] + amount,


Future<void> runInTransaction({
  @required Reach reach,
  @required Duration timeout,
  @required Future<void> Function(Transaction transaction) callback,
}) async {
  await adapter.performDocumentTransaction(DocumentTransactionRequest(
    reach: reach,
    callback: callback,
    timeout: timeout,