Dart/Flutter: How to Sort Map Key and Values with examples

The map is a data structure with keys and values in an unordered way.

This tutorial shows multiple ways to sort the map by key and values in Dart and Flutter.

One of the ways is using a collections package that contains SplayTreeMap🔗 class to store items in sorted order.

How to sort Map by Values in dart and flutter?

There are multiple ways to sort keys in a Map SplayTreeMap class provides a named constructor using the from method that accepts map and function. the function contains logic to sort keys with other keys in a map.

SplayTreeMap.from(map,function)

Here is an example program to sort keys in ascending and descending order.

import 'dart:collection';

void main() {
  var numbers = {'one': 1, 'two': 2, 'three': 3, 'four': 4};
  print(numbers); //{one: 1, two: 2, three: 3, four: 4}

  // Sort Map key in ascending order
  final sortedKeysAsc = SplayTreeMap<String, dynamic>.from(
      numbers, (keys1, keys2) => keys1.compareTo(keys2));
  print(sortedKeysAsc); //{four: 4, one: 1, three: 3, two: 2}

  // Sort Map key in descending order
  final sortedKeysDesc = SplayTreeMap<String, dynamic>.from(
      numbers, (keys1, keys2) => keys2.compareTo(keys1));
  print(sortedKeysDesc); //{two: 2, three: 3, one: 1, four: 4}
}

Output:

{one: 1, two: 2, three: 3, four: 4}
{four: 4, one: 1, three: 3, two: 2}
{two: 2, three: 3, one: 1, four: 4}

How to sort maps by value in dart and flutter?

This example sorts map values in ascending and descending order.

if values are compared using numbers[keys1].compareTo(numbers[keys2]) It throws an Error: Method ‘compareTo’ cannot be called on ‘int?’ because it is potentially null. The reason is about null value safety. We have to use numbers[keys1]!.compareTo(numbers[keys2]!)

Here is an example of SplayTreeMap sort key and values

import 'dart:collection';

void main() {
  var numbers = {'one': 1, 'two': 2, 'three': 3, 'four': 4};
  print(numbers); //{one: 1, two: 2, three: 3, four: 4}

  // Sort Map key in ascending order
  final sortedValuesAsc = SplayTreeMap<String, int>.from(
      numbers, (keys1, keys2) => numbers[keys1]!.compareTo(numbers[keys2]!));
  print(sortedValuesAsc); //{one: 1, two: 2, three: 3, four: 4}


  // Sort Map key in descending order
  final sortedValuesDesc = SplayTreeMap<String, dynamic>.from(
      numbers, (keys1, keys2) => numbers[keys2]!.compareTo(numbers[keys1]!));
  print(sortedValuesDesc); //{four: 4, three: 3, two: 2, one: 1}

}

Output:

{one: 1, two: 2, three: 3, four: 4}
{one: 1, two: 2, three: 3, four: 4}
{four: 4, three: 3, two: 2, one: 1}

Conclusion

You’ve learned how to sort maps based on key and values in dart and flutter programming.