How to Get Real time Updates From Firebase In Firebase

[亡魂溺海] 提交于 2020-06-29 03:47:41

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!