Issue
I want to add the data from into _list another list where the name is NS200. The list contains data like this.
List<Posts> _list = [
{id: "0",
name: "assa ",},
{id: "1",
name: "NS200",}];.
I tried using were but it’s not working.
Solution
where
returns an iterable which needs to be converted back to list as you are using list. Also, you are storing data incorrectly. List type is Posts
so you must store posts in the list rather than a map or list of maps. See the below code:
class Posts {
String id;
String name;
Posts({this.id, this.name});
}
void main() {
List<Posts> _items = [
Posts(
id: "1",
name: "NS200",
),
Posts(
id: "2",
name: "assa",
),
Posts(
id: "3",
name: "NS200",
),
];
List<Posts> _newList = [];
_newList = _items.where((item) => item.name == "NS200").toList();
for (var item in _newList) {
print('${item.id} - ${item.name}');
}
}
With where
, you can check whether the string you want to check matches with the name of every list item. If it matches, it will return true otherwise false. Then you can convert it to a list using toList()
.
You can wrap the filter logic in a function so you can call it whenever you want.
List<Posts> _newList = [];
void filterList() {
_newList = _items.where((item) => item.name == "NS200").toList();
}
filterList();
for (var item in _newList) {
print('${item.id} - ${item.name}');
}
Answered By – gegobyte
Answer Checked By – Senaida (FlutterFixes Volunteer)