Transaction class
Reads and writes documents inside a transaction started with FirebaseFirestore.runTransaction.
You never create a transaction yourself: FirebaseFirestore.runTransaction passes one to your function. A read-write transaction (the default) reads documents with get, then writes with set, update, update and delete. When the function completes, the writes are committed together, and only if none of the documents the function read has changed on the server since it read them.
final DocumentReference<Map<String, Object?>> counter =
firestore.doc('counters/visits');
final int next = await firestore.runTransaction<int>((
Transaction transaction,
) async {
final DocumentSnapshot<Map<String, Object?>> snapshot =
await transaction.get(counter);
final int value = (snapshot.data()?['value'] as int?) ?? 0;
transaction.set(counter, <String, Object?>{'value': value + 1});
return value + 1;
});
Rules for the function:
- Do every read before the first write. A get after a write fails with FirestoreErrorCode.invalidArgument, and so does the commit.
- The function can run several times. When a document it read changed
before the commit, the client runs it again after a backoff (about one
second at first, then longer), up to the
maxAttemptsattempts (5 by default). Keep side effects, such as changing your app's state, out of the function, or make them safe to repeat. - Errors with the codes FirestoreErrorCode.aborted, FirestoreErrorCode.alreadyExists and FirestoreErrorCode.failedPrecondition, and errors that a new attempt can fix (such as FirestoreErrorCode.unavailable), cause a retry, also when your function throws them. Any other error, and any error that is not a FirestoreException, ends the transaction: nothing is written and the future of FirebaseFirestore.runTransaction fails with that error. When the attempts are used up it fails with the last error, for example FirestoreErrorCode.failedPrecondition after repeated conflicts.
- Do not keep the transaction after the function has completed.
A transaction needs the backend: its reads never come from the local
cache, and it is not queued while the client is offline, unlike a
WriteBatch. Without a connection the reads or the commit fail, the
client retries until the attempts are used up, and then the future
fails. The writes of a transaction are sent to the server at commit and
are not applied to the local cache as pending writes: listeners see them
only once the server reports the change.
A read-only transaction (runTransaction(..., readOnly: true)) reads a
consistent snapshot of the database and can also run queries with
getQuery and aggregations with getAggregate; it cannot write. Read-only
transactions, getQuery and getAggregate are not in the JS client SDK;
they follow the server SDKs.
A commit that is lost on the way back can make the client retry a transaction that the backend already applied, so the same writes can be applied twice. The JS and Android SDKs have the same exposure. Make such writes idempotent where it matters.
Subclassing Note: Firestore classes are not meant to be subclassed except for use in test mocks. Subclassing is not supported in production code and new SDK releases may break code that does so.
- Available extensions
Properties
- hashCode → int
-
The hash code for this object.
no setterinherited
- runtimeType → Type
-
A representation of the runtime type of the object.
no setterinherited
Methods
-
delete(
DocumentReference< Object?> documentRef) → Transaction -
Deletes the document
documentRefwhen the transaction commits. -
execute(
Pipeline pipeline, {PipelineIndexMode? indexMode, PipelineExplainOptions? explainOptions, Map< String, Object?> ? rawOptions}) → Future<PipelineSnapshot> -
Available on Transaction, provided by the TransactionPipelines extension
Executespipelineon the server inside this transaction. Only in a read-only transaction (runTransaction(..., readOnly: true)): the pipeline reads the snapshot of the database that every read of the transaction sees. -
get<
T extends Object?> (DocumentReference< T> documentRef) → Future<DocumentSnapshot< T> > -
Reads the document
documentReffrom the server. -
getAggregate(
AggregateQuery aggregateQuery) → Future< AggregateQuerySnapshot> -
Runs the aggregation
aggregateQueryon the server inside this transaction. Only in a read-only transaction, like getQuery: the aggregation is computed over the snapshot of the database that every read of the transaction sees. -
getQuery<
T extends Object?> (Query< T> query) → Future<QuerySnapshot< T> > -
Runs
queryon the server inside this transaction and returns its results. Only in a read-only transaction (runTransaction(..., readOnly: true)): the documents are those of the snapshot of the database that every read of the transaction sees. -
noSuchMethod(
Invocation invocation) → dynamic -
Invoked when a nonexistent method or property is accessed.
inherited
-
set<
T extends Object?> (DocumentReference< T> documentRef, T data, [SetOptions? options]) → Transaction -
Writes
datato the documentdocumentRefwhen the transaction commits: the document is created if it does not exist, and replaced if it does. -
toString(
) → String -
A string representation of this object.
inherited
-
update(
DocumentReference< Object?> documentRef, Map<Object, Object?> data) → Transaction -
Updates the fields in
dataof the existing documentdocumentRefwhen the transaction commits. Fields that are not indatakeep their values.
Operators
-
operator ==(
Object other) → bool -
The equality operator.
inherited