Home > OS >  Flutter - Get or access to matching map(s) from a List of Maps
Flutter - Get or access to matching map(s) from a List of Maps

Time:11-05

Here I have a list of maps.

[
  {
    'name': 'name1',
    'age': 30,
  },
  {
    'name': 'name2',
    'age': 20,
  },
  {
    'name': 'name1',
    'age': 15,
  },
]

I need to access to 'name': 'name1' map from above list.

-- Access or extract maps --

i. e. List[0] and(or) List[2]

How do I do this kind of thing???

CodePudding user response:

You can loop through the list and find items, .where will return list of found item. .firstWhere for single item return.

 final data = [
      {
        'name': 'name1',
        'age': 30,
      },
      {
        'name': 'name2',
        'age': 20,
      },
      {
        'name': 'name1',
        'age': 15,
      },
    ];

    final findValue = "name1";

    final result = data.where((element) => element["name"] == findValue);
    print(result); //({name: name1, age: 30}, {name: name1, age: 15})

    result.forEach((element) {
      print("${element["name"]} ${element["age"]}");
    });

More about List

  • Related