在我们做App中列表时少不了进行数据排序,比如城市列表等等,再Flutter中List是怎么排序的呢,Flutter的框架基础是Dart所以我们还是要回归Dart
先给大家看效果吧
![效果图]:https://upload-images.jianshu.io/upload_images/2204230-6cbfa213548d2c17.PNG?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240
官方介绍
void sort([int compare(E a, E b)]);
/**
* Sorts this list according to the order specified by the [compare] function.
*
* The [compare] function must act as a [Comparator].
*
* List numbers = ['two', 'three', 'four'];
* // Sort from shortest to longest.
* numbers.sort((a, b) => a.length.compareTo(b.length));
* print(numbers); // [two, four, three]
*
* The default List implementations use [Comparable.compare] if
* [compare] is omitted.
*
* List nums = [13, 2, -11];
* nums.sort();
* print(nums); // [-11, 2, 13]
*
* A [Comparator] may compare objects as equal (return zero), even if they
* are distinct objects.
* The sort function is not guaranteed to be stable, so distinct objects
* that compare as equal may occur in any order in the result:
*
* List numbers = ['one', 'two', 'three', 'four'];
* numbers.sort((a, b) => a.length.compareTo(b.length));
* print(numbers); // [one, two, four, three] OR [two, one, four, three]
*/
官方路径
:https://api.dartlang.org/stable/2.4.0/dart-core/List/sort.html
所以对于List
List brands = List.from(val.data);
brands.sort((ak, bk) {
/**
我的dynamic是{key:value},这种结构, 所以使用了Map,如果List中是String,可以直接codeUnits
关于 codeUnits:返回此字符串的UTF-16代码单元的不可修改列表。
[https://api.dartlang.org/stable/2.4.0/dart-core/String/codeUnits.html](https://api.dartlang.org/stable/2.4.0/dart-core/String/codeUnits.html)
**/
Map aj = Map.from(ak);
Map bj = Map.from(bk);
List al = '${aj['brand_en']}'.codeUnits;
List bl = '${bj['brand_en']}'.codeUnits;
for (int i = 0; i < al.length; i++) {
if (bl.length <= i) return 1;
if (al[i] > bl[i]) {
return 1;
} else if (al[i] < bl[i]) return -1;
}
return 0;
});
codeUnits
:https://api.dartlang.org/stable/2.4.0/dart-core/String/codeUnits.html