在您使用List<Map<String, String>> 的情况下,您应该实现自己的比较函数。
void main() {
final list = [
{'name': 'Item001', 'type': 'RESULT'},
{'name': 'Item002', 'type': 'OTHER'},
{'name': 'Item005', 'type': 'GAME'},
{'name': 'Item0039', 'type': 'RESULT'},
];
int _compare(Map<String, String> map1, Map<String, String> map2) {
var compare;
if (map1['type'] == map2['type'])
compare = 0;
else if (map1['type'] == 'RESULT' && map2['type'] == 'GAME')
compare = -2;
else if (map1['type'] == 'RESULT' && map2['type'] == 'OTHER')
compare = -1;
else if (map1['type'] == 'GAME' && map2['type'] == 'OTHER')
compare = -1;
else
compare = 1;
return compare;
}
test('sorting_this_list', () {
list.sort(_compare);
print('\n');
list.forEach(print);
});
}
如果您添加新的不同类型字符串,则必须向比较函数添加逻辑。将此代码放入您的测试文件中,它将打印:
{name: Item001, type: RESULT}
{name: Item0039, type: RESULT}
{name: Item005, type: GAME}
{name: Item002, type: OTHER}
来自可比较的文档。
/**
* The signature of a generic comparison function.
*
* A comparison function represents an ordering on a type of objects.
* A total ordering on a type means that for two values, either they
* are equal or one is greater than the other (and the latter must then be
* smaller than the former).
*
* A [Comparator] function represents such a total ordering by returning
*
* * a negative integer if [a] is smaller than [b],
* * zero if [a] is equal to [b], and
* * a positive integer if [a] is greater than [b].
*/
typedef Comparator<T> = int Function(T a, T b);