void main() {
var x = {'b': 10, 'c': 7, 'a': 2};
print('x = $x');
final y = x.orderByKeys(compareTo: (a, b) => a.compareTo(b));
final z = x.orderByValues(compareTo: (a, b) => a.compareTo(b));
print('y = $y');
print('z = $z');
}
/// Extensions on [Map] of <[dynamic], [dynamic]>
extension ExtendsionsOnMapDynamicDynamic on Map<dynamic, dynamic>{
/// Order by keys
Map<dynamic, dynamic> orderByKeys({required int Function(dynamic a, dynamic b) compareTo}) {
return Map.fromEntries(entries.toList()..sort((a, b) => compareTo(a.key, b.key)));
}
/// Order by values
Map<dynamic, dynamic> orderByValues({required int Function(dynamic a, dynamic b) compareTo}) {
return Map.fromEntries(entries.toList()..sort((a, b) => compareTo(a.value, b.value)));
}
}
6条答案
按热度按时间0sgqnhkj1#
在Dart中,它被称为
SplayTreeMap
:gmol16392#
如果你想要一个排序
List
的Map键:您可以选择将自定义排序函数传递给
List.sort
方法。最后,我是否可以建议使用
Map<String, dynamic>
而不是Map<String, Object>
?dgsult0t3#
如所见
How to use a SplayTreeMap on Firebase snapshot dictionary in dart/Flutter?
s5a0g9ez4#
我知道我的答案已经太迟了,但看看我发现了什么。也许能帮上什么人
这个sortedmap包有助于以排序的方式维护对象的Map。
5us2dqdw5#
我想是的。
ckx4rj1h6#
我建议使用以下代码: