Terminator
Terminator

Reputation: 103

How to search in list of maps by key

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',

  },
]

Upvotes: 2

Views: 2236

Answers (4)

eamirho3ein
eamirho3ein

Reputation: 17950

Try this:

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

Upvotes: 1

Krish Bhanushali
Krish Bhanushali

Reputation: 2052

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.

Upvotes: 4

Irfan Ganatra
Irfan Ganatra

Reputation: 1398

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

Upvotes: 1

Terminator
Terminator

Reputation: 103

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;
}

Upvotes: 0

Related Questions