如何在Dart中过滤列表

时间:2019-07-09 19:30:09

标签: firebase flutter dart google-cloud-firestore

我正在从Firebase中获取我的DocumentSnapshots,并且试图删除用户ID匹配但userList始终返回4条记录的文档。

List<DocumentSnapshot> userList = new List<DocumentSnapshot>();

                        userList = snapshot.data.documents.map((DocumentSnapshot docSnapshot) {
                          //print("ACTUAL USER :: " + docSnapshot.data['userId']);
                          if (docSnapshot.data['userId'] != id) {
                            return docSnapshot;
                          } else {
                            print('FOUND IT: ' + id);
                            userList.remove(docSnapshot.data);
                            //userList.removeWhere((docSnapshot) => 'userId' == id);
                          }
                        }).toList();

print('userList Size: ' + userList.length.toString());

验证有效(“找到了”),但是我的测试都无法从文档列表中删除用户。

有人可以建议吗?

1 个答案:

答案 0 :(得分:0)

您正在尝试从List中删除元素,甚至还没有添加它。
具体来说,map函数将在映射快照后的后向您的List变量分配一个userList
从您的代码中,我可以看出您实际上并不想执行任何 mapping ,而只想执行 filtering

在Dart中,您可以使用Iterable.where进行过滤。
在您的情况下,看起来像这样:

final List<DocumentSnapshot> userList = snapshot.data.documents
      .where((DocumentSnapshot documentSnapshot) => documentSnapshot['userId'] != id).toList();

我假设您只希望没有 userId的{​​{1}}的文档,否则,您将不得不使用id运算符

您还可以使用List.removeWhere,方法是先将所有文档分配给==,然后再调用userList

removeWhere