snapshots method

Stream<DocumentSnapshot<T>> snapshots({
  1. bool includeMetadataChanges = false,
  2. ListenSource source = ListenSource.defaultSource,
})

A stream of snapshots of this document: the current contents first, then a new snapshot every time the contents change.

The first snapshot can come from the local cache before the backend answers. A document that does not exist (or is deleted) gives a snapshot whose DocumentSnapshot.exists is false. Local writes raise a snapshot at once, with metadata.hasPendingWrites true. While the client is offline the stream keeps delivering changes from the cache.

With includeMetadataChanges a snapshot also arrives when only the DocumentSnapshot.metadata changed (for example when a local write is acknowledged). With ListenSource.cache as source the events come from the local cache only and the backend is not contacted for this listener.

The listener is registered when you listen to the stream and removed when you cancel the subscription. Each call returns a new single-subscription stream. An error (for example FirestoreErrorCode.permissionDenied) is delivered on the stream, which then closes. A listener that subscribes later does not see earlier snapshots: the stream starts with the current state of the document.

final StreamSubscription<DocumentSnapshot<Map<String, Object?>>> subscription =
    firestore
        .doc('cities/SF')
        .snapshots()
        .listen(
          (DocumentSnapshot<Map<String, Object?>> snapshot) {
            print(snapshot.exists ? snapshot.data() : 'no such document');
          },
          onError: (Object error) => print('listen failed: $error'),
        );
// ...
await subscription.cancel();

firestore.doc('cities/SF').snapshots(includeMetadataChanges: true).listen((
  DocumentSnapshot<Map<String, Object?>> snapshot,
) {
  final bool saved = !snapshot.metadata.hasPendingWrites;
  print(saved ? 'saved on the server' : 'local change, not saved yet');
});

Implementation

Stream<DocumentSnapshot<T>> snapshots({
  bool includeMetadataChanges = false,
  ListenSource source = ListenSource.defaultSource,
}) {
  return _getSnapshotsInternal(
    _internalOptions(includeMetadataChanges, source),
  );
}