How can I find out if a List of Maps contain a specific value for key?
I'm having trouble understanding how to check if a List of Maps contain a value by a key. Below is the structure of data I have.
[
{
id: 1,
bookTxt: Hereissomebooktext.,
bookAuth: Charles
},
{
id: 3,
bookTxt: Hereissomemorebooktext.,
bookAuth: Roger
},
{
id: 6,
bookTxt: Hereissomeevenmorebooktext.,
bookAuth: Matt
}
]
I'm trying to write something simple or a function to see if this List of Maps contains a certain 'id'. I know that List has the Contains method but in my case I have to find a value within a list of Maps.
For example if I want to see if the List of Maps above contains the id
of 3
, how would I be able to access that?
Direct way to check
if (list[0].containsKey("id")) {
if (list[0]["id"] == 3) {
// your list of map contains key "id" which has value 3
}
}
And for indirect way you need to iterate through the loop like this:
for (var map in list) {
if (map?.containsKey("id") ?? false) {
if (map!["id"] == 3) {
// your list of map contains key "id" which has value 3
}
}
}