The default map class is insertion-ordered on the keys.
The easiest approach is to just create a new map with the same entries, added in the order you want.
First, let's find the order you want:
var sortedEntries = map.entries.toList()..sort((e1, e2) {
var diff = e2.value.compareTo(e1.value);
if (diff == 0) diff = e2.key.compareTo(e1.key);
return diff;
});
(This assumes that your keys and values are all Comparable
, otherwise you need to figure out how to compare them yourself. In this particular case, where keys are String
s and values are int
s, it's only null
keys or values that may be incomparable).
This orders the entries in reverse value order, and for equal values, in reverse key order.
You can then create a new map from those entries:
var newMap = Map<String, int>.fromEntries(sortedEntries);
or you can modify the existing map by removing the old entries and adding the new:
map..clear()..addEntries(sortedEntries)
or
for (var entry in sortedEntries) {
map..remove(entry.key)..[entry.key] = entry.value;
}
There is no functionality on the map class itself to order its entries.