这里你可能会发现,这里的 sort 函数和 Swift 的略有不同,内部回调的返回值不是 bool 而是 int 。
结合函数头文件注释我们可以了解更多:
/// Sorts this list according to the order specified by the [compare] function.
///
/// The [compare] function must act as a [Comparator].
/// ```dart
/// var 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.
/// ```dart
/// List<int> nums = [13, 2, -11];
/// nums.sort();
/// print(nums); // [-11, 2, 13]
/// ```
/// In that case, the elements of the list must be [Comparable] to
/// each other.
///
/// 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:
/// ```dart
/// var 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]
/// ```
void sort([int compare(E a, E b)?]);
简略写法
这里的排序函数可以在条件比较简单的情况下可以简写,提高编码效率
未简写
sort((a, b) {
if (a.indexLetter == null || b.indexLetter == null) {
return 0;
}
return a.indexLetter!.compareTo(b.indexLetter!);
});
简写
sort( (a, b) => a.indexLetter.compareTo(b.indexLetter) );