简体   繁体   English

如何在 Dart 中过滤列表

[英]How to filter a List in Dart

I'm getting my DocumentSnapshots from Firebase and I'm trying to delete the document where the user ID match but the userList is always returning the 4 records.我正在从 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());

The validation works ("Found it") but none of my tests where able to delete the user from document list.验证有效(“找到”),但我的测试中没有一个能够从文档列表中删除用户。

Can someone advise please?有人可以建议吗?

You are trying to remove the element from your List before it was even added.您试图在添加元素之前将其从List删除。
Specifically, the map function will assign a List to your userList variable after it has mapped the snapshots.具体来说, map函数会映射快照为您的userList变量分配一个List
From your code I can tell that you do not actually want to perform any mapping but only filtering .从您的代码中,我可以看出您实际上并不想执行任何映射,而只想执行过滤

In Dart, you can filter using the Iterable.where .在 Dart 中,您可以使用Iterable.where进行过滤。
In your case that would look something like this:在您的情况下,它看起来像这样:

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

I am assuming that you only want documents that do not have a userId of id , otherwise, you would have to use an == operator instead.我假设您只需要没有userId id文档,否则,您将不得不使用==运算符。

You could also useList.removeWhere by assigning all the documents to your userList first and then calling removeWhere :你也可以使用List.removeWhere通过分配所有的文件到你的userList ,然后再调用removeWhere

final List<DocumentSnapshot> userList = snapshot.data.documents;

userList.removeWhere((DocumentSnapshot documentSnapshot) => documentSnapshot['userId'] != id).toList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM