How to filter a List in Dart
Solution 1:
You are trying to remove the element from your List
before it was even added.
Specifically, the map
function will assign a List
to your userList
variable after it has mapped the snapshots.
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
.
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.
You could also use List.removeWhere
by assigning all the documents to your userList
first and then calling removeWhere
:
final List<DocumentSnapshot> userList = snapshot.data.documents;
userList.removeWhere((DocumentSnapshot documentSnapshot) => documentSnapshot['userId'] != id).toList();