Home > Back-end >  how to loop map value by key
how to loop map value by key

Time:06-11

i usually loop a list<Map<String, dynamic>> with for(var item in list) / for(var i=0; i<list.length; i ) for list like this. Usually i just call for(var item in list2) item['value']

List<Map<String, dynamic>> list2 = [
    {
      'value': 'Value number one',
    },
    {
      'value': 'Value number two',
    },
  ];

but then i have a list that looks like this, since every item has different keys i cannot use this anymore for(var item in list) item['value']. How to loop and get all the value ?

  List<Map<String, dynamic>> list = [
    {

      '1': {
        'value': 'Value number one',
      },

      '2': {
        'value': 'Value number two',
      },

    }
  ];

CodePudding user response:

Your dummyData is a list of map though it contains only a single map.

If you just want to get values from Map using key, you can get list of keys 1st. or myMap.values.toList()

Map<String, dynamic> myMap = {};
List<String> keys = myMap.keys.toList();
List<dynamic> values = myMap.values.toList();

For List<Map<String, dynamic>>


  List<String> dummyDataKeys = [];
  List<dynamic> dummyDataValues = [];
  for (final item in dummyData) {
    // dummyDataKeys = [
    //   ...dummyDataKeys,
    //   ...item.keys.toList(),
    // ];
    dummyDataKeys.addAll(item.keys.toList());
    dummyDataValues.addAll(item.values.toList());
  }

More about Map and List.

CodePudding user response:

try this code is simple :

 for(var item in list){

    for(var item2 in item.values){
  
        print(item2['value']);

    } 
}
  • Related