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?
HashMap get() Method in Java util. HashMap. get() method of HashMap class is used to retrieve or fetch the value mapped by a particular key mentioned in the parameter. It returns NULL when the map contains no such mapping for the key.
containsKey() function in Dart is used to check if a map contains the specific key sent as a parameter. map. containsKey() returns true if the map contains that key, otherwise it returns false .
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
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With