get method
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:
- Source.serverAndCache (the default): waits for the backend; when the client is offline it answers from the cache, and fails with FirestoreErrorCode.unavailable if the cache has no copy of the document.
- Source.server: fails with FirestoreErrorCode.unavailable when the backend cannot be reached.
- Source.cache: answers from the cache only; fails with FirestoreErrorCode.unavailable when the cache does not know the document. A document the cache knows to be missing gives a snapshot whose DocumentSnapshot.exists is false.
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);
}
}