问题
I've been trying to get Firebase to work real time and i have a couple of issues. What i want to achieve is to be able to tell when a new document is added to a collection, just that, nothing more. What seems to be happening is my code always returns all the documents in the collection.
Below is my code:
listenNewPost(int categoryId, Users user, Function(DocumentSnapshot) onData) async {
var ref = this._firestore.collection('posts').reference();
var query = ref.orderBy('created_at', descending: true);
var _query = ref.where('category', isEqualTo: categoryId).orderBy('created_at', descending: true);
if (categoryId == 1) {
query.snapshots().listen((snapshot) {
snapshot.documentChanges.forEach((doc) {
if (doc.type == DocumentChangeType.added) {
print('receieved: ' + doc.document.data.toString());
onData(doc.document);
}
});
});
}
else {
_query.snapshots().listen((snapshot) {
snapshot.documentChanges.forEach((doc) {
if (doc.type == DocumentChangeType.added) {
print('_receieved: ' + doc.document.data.toString());
onData(doc.document);
}
});
});
}
}
I have another code that get all posts and i want to use this in that current screen to get all new posts so i don't have to use a timer to refresh the screen. I have a getAllPosts method which runs before the above code. The getAllPosts gets all the posts successfully and the listener code also gets all posts instead of waiting when a new post is added. Below is how i am calling the codes:
Because am using Flutter, this is my code:
void initState() {
super.initState();
this.allPosts = [];
SOmeClass.listenNewPost();
this.getAllPosts();
}
What am I doing wrong please ? Thank You.
回答1:
When you first attach a listener to that query, the QuerySnapshot.documentChanges will contain a DocumentChangeType.added for each document that matches the query.
If you only want to retrieve documents that were created after a certain time, you'll have to add that condition to your query:
var query = ref.orderBy('created_at', descending: true);
query = query.where('created_at', '>=', new DateTime.now());
来源:https://stackoverflow.com/questions/62388503/how-to-get-real-time-updates-from-firebase-in-firebase