I would like to have a listener method that checks for changes to a collection of documents if changes occur.
Something like:
import 'package:cloud_firestore/cloud_firestore.dart';
Future<Null> checkFocChanges() async {
Firestore.instance.runTransaction((Transaction tx) async {
CollectionReference reference = Firestore.instance.collection('planets');
reference.onSnapshot.listen((querySnapshot) {
querySnapshot.docChanges.forEach((change) {
// Do something with change
});
});
});
}
The error here is that onSnapshot
isn't defined on CollectionReference
.
Any ideas?
Reading through cloud_firestore
's documentation you can see that a Stream
from a Query
can be obtained via snapshots()
.
For you to understand, I will transform your code just a tiny bit:
CollectionReference reference = Firestore.instance.collection('planets');
reference.snapshots().listen((querySnapshot) {
querySnapshot.documentChanges.forEach((change) {
// Do something with change
});
});
You should also not run this in a transaction. The Flutter way of doing this is using a StreamBuilder
, straight from the cloud_firestore
Dart pub page:
StreamBuilder<QuerySnapshot>(
stream: Firestore.instance.collection('books').snapshots(),
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (!snapshot.hasData) return new Text('Loading...');
return new ListView(
children: snapshot.data.documents.map((DocumentSnapshot document) {
return new ListTile(
title: new Text(document['title']),
subtitle: new Text(document['author']),
);
}).toList(),
);
},
);
If you want to know any more, you can take a look at the source, it is well documented, where it is not self-explanatory.
Also take note that I changed docChanges
to documentChanges
. You can see that in the query_snapshot
file. If you are using an IDE like IntelliJ or Android Studio, it is also pretty easy to click through the files in it.