I have the following list
List<Map<String, dynamic>> filterItems = [
{"category":1},
{"option_val":1},
]
I also have the following map
Map<String, dynamic> singleItem = {"category":6}
I would like to remove any item from the list above (filterItems) which has an object with key similar to singleItem map. So in my case i would like to remove the {"category":1}
from the list since it has a key category similar to the map.
So i have tried the following
filterItems.remove(singleItem);
print(filterItems)
But the above doesnt work since the value of key is different so i tried the following where am now stuck on how to proceed
singleItem.map((key,value){
filterItems.removeWhere((element) => element.containsKey(key))
})
But the above throws an error that the body of singleItem.map
is returning null. How can I proceed to remove an item from the list when a key matches even though the value is different?
CodePudding user response:
you can use .removeWhere
as follow:
List<Map<String, dynamic>> filterItems = [
{"category":1},
{"option_val":1},
];
Map<String, dynamic> singleItem = {"category":6};
filterItems.removeWhere((element) => element.keys.first == singleItem.keys.first);
print(filterItems);
and the result would be:
[{option_val: 1}]
CodePudding user response:
- Remove when a list has the same key
List<Map<String, dynamic>> filterItems = [
{"category": 1},
{"option_val": 1},
];
Map<String, dynamic> singleItem = {"category": 6};
filterItems = filterItems.where((e) {
return e.keys.toString() != singleItem.keys.toString();
}).toList();