Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I find out if a List of Maps contain a specific value for key?

Tags:

flutter

dart

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?

like image 508
kelsheikh Avatar asked Aug 18 '19 11:08

kelsheikh


People also ask

How do you find the specific value of a key on a map?

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.

How do you check if a map contains a key or not in flutter?

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 .


1 Answers

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
    }
  }
}
like image 133
CopsOnRoad Avatar answered Nov 08 '22 04:11

CopsOnRoad