如何在 Dart 中过滤列表

Fil*_*eOS 2 dart firebase flutter 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());
Run Code Online (Sandbox Code Playgroud)

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

有人可以建议吗?

cre*_*not 6

List您正试图在添加该元素之前将其从您的元素中删除。
具体来说,该函数在映射快照map会将 a 分配List给您的userList变量。 从您的代码中我可以看出您实际上不想执行任何映射而只想执行过滤

在 Dart 中,您可以使用Iterable.where.
在你的情况下,看起来像这样:

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

我假设您只需要没有ofuserId的文档id,否则,您将不得不使用==运算符。

您还可以List.removeWhere通过将所有文档分配给您的userList第一个文档然后调用removeWhere

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

userList.removeWhere((DocumentSnapshot documentSnapshot) => documentSnapshot['userId'] != id).toList();
Run Code Online (Sandbox Code Playgroud)