Skip to main content

Flutter Dart Sort Map by Key Value in Ascending Order

When there are large amount of data in hundreds of records then there might be Map keys is not in order few times. So we can manually set order of Map object data by Key value in ascending order. After filtering all the data keys will be in 1, 2, 3, 4, 5 So on order.

Flutter Dart Sort Map by Key Value in Ascending Order

1. Creating a test map object with 10 items. We will shuffle the items in wrong order.
Map testMap = {10: 'T', 8: 'E', 6: 'S', 4: 'F', 2: 'T', 9: 'N', 7: 'S', 5: 'F', 3: 'T', 1: 'O'};
2. Creating a variable and define Map.fromEntries() method and filter one by one all the map values in key ascending order.
var sortedMap = Map.fromEntries(
    testMap.entries.toList()..sort((e1, e2) => e1.key.compareTo(e2.key)));
Source code for main.dart file:
void main() {
  
Map testMap = {10: 'T', 8: 'E', 6: 'S', 4: 'F', 2: 'T', 9: 'N', 7: 'S', 5: 'F', 3: 'T', 1: 'O'};

print(testMap);
var sortedMap = Map.fromEntries(
    testMap.entries.toList()..sort((e1, e2) => e1.key.compareTo(e2.key)));

print(sortedMap);
  
}
Output:
Flutter Dart Sort Map by Key Value in Ascending Order

Comments