get method

Future<DocumentSnapshot<T>> get([
  1. GetOptions? options
])

Reads the document referenced by this DocumentReference.

By default, get attempts to provide up-to-date data when possible by waiting for data from the server, but it may return cached data or fail if you are offline and the server cannot be reached. This behavior can be altered with options.

The GetOptions.source of options configures the get behavior:

Returns a Future that will be resolved with a DocumentSnapshot of the document at this DocumentReference. A document that does not exist gives a snapshot whose DocumentSnapshot.exists is false; it is not an error. Writes that the backend has not acknowledged yet are included. This is the JS SDK getDoc, getDocFromServer and getDocFromCache.

final DocumentSnapshot<Map<String, Object?>> snapshot = await firestore
    .doc('cities/SF')
    .get();
if (snapshot.exists) {
  print(snapshot.data());
}

final DocumentSnapshot<Map<String, Object?>> cached = await firestore
    .doc('cities/SF')
    .get(const GetOptions(source: Source.cache));

Implementation

Future<DocumentSnapshot<T>> get([GetOptions? options]) async {
  final Source source = options?.source ?? Source.serverAndCache;

  if (source == Source.cache) {
    final Document? doc = await firestore.client.getDocumentFromLocalCache(
      key,
    );
    final bool hasPendingWrites = doc != null && doc.hasLocalMutations;

    return DocumentSnapshotInternal.create<T>(
      firestore,
      key,
      doc,
      isFromCache: true,
      hasPendingWrites: hasPendingWrites,
      converter: converter,
    );
  } else {
    return _getViaSnapshotListener(source);
  }
}