Из этого ответа мы можем понять, что вызов .snapshots()
возвращает объект Stream
, чего мы и хотим.Это будет возможно из запросов, ссылок на коллекции и ссылок на документы.Вам понадобится позже.
Во-первых, сохраните ссылку на каждый документ в самой модели, добавьте ее также в конструкторы, чтобы вы всегда могли передать ее при создании объектов из DocumentSnapshot
, напримерthis:
import 'package:cloud_firestore/cloud_firestore.dart';
class TaskList {
/* attributes */
DocumentReference reference; //Add this
// If you followed the default firebase guide, you'll have the following methods.
// Add the reference to your constructors
TaskList.fromMap(Map<String, dynamic> map, {this.reference}) //add this reference
: //normal attribute initializations;
TaskList.fromSnapshot(DocumentSnapshot snapshot)
: this.fromMap(snapshot.data, reference: snapshot.reference); //add this reference as well
...
}
Теперь для каждого документа вы будете использовать ссылочный атрибут, получать моментальные снимки и прослушивать этот поток:
TaskList taskList = TaskList.fromSnapshot(doc); //normal initialization
taskList.reference.snapshots().listen((updatedDoc){ //listen to the stream
print("Document was updated:");
print(updatedDoc.data);
// notice that this will return the first time with the object itself
// which can be resource consuming
});
return MapEntry(doc.documentID, taskList);