Home > database >  How to search in list of maps by key
How to search in list of maps by key

Time:11-06

I have a list of map and I want to get the map of specific key for example : video of letter a

List<Map<String, String>> letters = const [
  {
    'letter': 'a',
    'name' : 'ddd',
    'video' : 'ss',

  },
  {
    'letter': 'b',
    'name' : 'ddd',
    'video' : 'ss',

  },
  {
    'letter': 'c,
    'name' : 'ddd',
    'video' : 'ss',

  },
]

CodePudding user response:

I guess you can use .where method like this

List listWithVideo = letters.where((element) => element['letter'] == 'a').toList();

Now here you will get list of maps where you will find your letter a.

If you want to get only one map or the first map that has the same, you can also use firstWhere method.

CodePudding user response:

I am also beginner,but here is my effort


void main() {
  List<Map<String, String>> letters = const [
  {
    'letter': 'a',
    'name': 'ddd',
    'video': 'ss',

  }
  ,
{
  'letter': 'b',
  'name' : 'ddd',
  'video' : 'ss',

  },
  {
  'letter': 'c',
  'name' : 'ddd',
  'video' : 'ss',

  },
  ];



  Map<String,dynamic> lst=letters.firstWhere((element) {

    return element['letter']=='a';
  });

  print(lst['video']);



}

its showing correct output

CodePudding user response:

Try this:

Map<String, dynamic> getAMap() {
    var list = letters.where((element) => element["letter"] == "a").toList();
    return list.isNotEmpty ? list.first : {};
  }

CodePudding user response:

I found a way to do this , so i can use the index and get the data that i want from the map

int search (String letter){
  int index=0;
  for ( var i=0 ; i<list.length;i   )
  {
    if (list[i]['letter']==letter){
      index=i;
    }
  }
  return index;
}
  • Related