首页 > 解决方案 > 如何在flutter中避免第一次从firestore中满载内容

问题描述

仅当集合中有任何更改时,我才想收听内容。但是当我尝试时StreamSubscription,所有内容都是第一次加载。

第一次如何避免满载?

 static StreamSubscription<dynamic> listenMessageChange(Function contentChange) {
    return Firestore.instance
        .collection('contents')
        .snapshots()
        .listen((data) {
          List<Message> changedContents = [];
          data.documentChanges.forEach((change) {
            changedContents.add(Content.createFromMap(change.document.data));
          });
          contentChange(changedContents);
    }, cancelOnError: false);
  }

标签: firebaseflutterdartgoogle-cloud-firestorelistener

解决方案


在侦听实时更新时,首先将检索所有数据。避免完全加载内容的唯一方法是使用该方法limit(),这样您就不会在第一次加载时获得所有内容。之后,您可以检查更改/添加/删除的文档:

Firestore.instance
        .collection('contents')
        .snapshots()
        .listen((data) {
      data.documentChanges.forEach((res) {
      if (res.type == DocumentChangeType.added) {
        print("added");
        print(res.document.data);
      } else if (res.type == DocumentChangeType.modified) {
        print("modified");
        print(res.document.data);
      } else if (res.type == DocumentChangeType.removed) {
        print("removed");
        print(res.document.data);
      }
    });

推荐阅读