get array of particular key from List<Map<String,dynamic>> in DART

Viewed 7186

I have a list with the below values:

List<Map<String, dynamic>> arrayTest = [{'id':'1','name':'test1'},{'id':'2','name':'test2'},{'id':'3','name':'test3'},{'id':'4','name':'test5'}];

I want to get all id values from the arrayTest variable into another List<dynamic> type list.

I'm new to flutter, I've tried the .map() function but not getting any idea how to do this.

2 Answers

This will help you !

List<dynamic> newList= arrayTest.map((m)=>m['id']).toList();
//replace m['id'] with your field !

I am not sure what you wanted, also please add expected output in your asked question.

Is that what you wanted:

void main() {
List<Map<String,dynamic>> arrayTest = [{'id':'1','name':'test1'},{'id':'2','name':'test2'},{'id':'3','name':'test3'},{'id':'4','name':'test5'}];

  List list=[];
  for(var array in arrayTest){
    list.add(array['name']);

  }
  print(list);
}

OR
without for loop

void main() {
List<Map<String,dynamic>> arrayTest = [{'id':'1','name':'test1'},{'id':'2','name':'test2'},{'id':'3','name':'test3'},{'id':'4','name':'test5'}];


  List list= arrayTest.map((array)=>array['name']).toList();
  print(list);
}



output:

[test1, test2, test3, test5]
Related