How to sort this using its items?

Viewed 48

I have a this list

List myList = [
    {'name':'user3', 'id':'3'},
    {'name':'user5', 'id':'5'},
    {'name':'user2', 'id':'2'},
    {'name':'user4', 'id':'4'},
    {'name':'user1', 'id':'1'}
  ];

I want to sort this list in the basis of 'id' but I am unable to understand the logic to do so

Basically what I want should be look like this after sorting

List myList = [
    {'name':'user1', 'id':'1'},
    {'name':'user2', 'id':'2'},
    {'name':'user3', 'id':'3'},
    {'name':'user4', 'id':'4'},
    {'name':'user5', 'id':'5'}
  ];
1 Answers

You can pass a callback to the sort method that will compare two elements against each other by your custom criteria.

List<Map<String, String>> myList = [
  {'name': 'user3', 'id': '3'},
  {'name': 'user5', 'id': '5'},
  {'name': 'user2', 'id': '2'},
  {'name': 'user4', 'id': '4'},
  {'name': 'user1', 'id': '1'}
];

void main() {
  myList.sort((a, b) => a['id']!.compareTo(b['id']!));
  print(myList);
}
Related