Flutter中如何对Uint8List或List<int>列表进行排序?
在Flutter中对Uint8List/List列表排序的实现方法
Flutter中List的默认sort方法无法直接按字典序比较嵌套的List<int>或Uint8List(Uint8List是List<int>的子类),需要自定义比较器来实现和JavaScript中Uint8Array.sort()一致的行为。
实现思路
核心是逐个对比两个列表的元素:
- 遍历两个列表的公共长度部分,找到第一个不相等的元素,返回两者的差值(正数则前者排后,负数则前者排前)
- 如果其中一个列表是另一个的前缀,则较短的列表排在前面
代码实现
首先定义通用的比较函数:
import 'dart:typed_data'; import 'dart:math'; int compareByteLists(List<int> a, List<int> b) { final minLen = min(a.length, b.length); for (int i = 0; i < minLen; i++) { final diff = a[i] - b[i]; if (diff != 0) { return diff; } } // 前面元素全相同,按长度排序 return a.length - b.length; }
然后使用这个比较器对列表排序:
void main() { // 对Uint8List列表排序 final uint8List = [ Uint8List.fromList([1, 2, 3]), Uint8List.fromList([0, 1, 2]), Uint8List.fromList([0, 1, 2, 4]), Uint8List.fromList([0]), ]; uint8List.sort(compareByteLists); for (var item in uint8List) { print(item); // 输出:[0], [0, 1, 2], [0, 1, 2, 4], [1, 2, 3] } // 对普通List<int>列表排序 final intList = [ [1, 2, 3], [0, 1, 2], ]; intList.sort(compareByteLists); print(intList); // 输出:[[0, 1, 2], [1, 2, 3]] }
说明
- 这个比较器同时适用于
Uint8List和普通List<int>,因为Uint8List继承自List<int> - 排序逻辑和JavaScript中
Uint8Array.sort()的默认行为完全一致,按字节的字典序排列
内容的提问来源于stack exchange,提问作者redDwarf
相关产品推荐
相关产品推荐

