[英]How to sort a list of tuples having mixed type elements in reverse order?
[英]Sort list and order by type in Flutter
例如,我有以下列表結構:
{
'name': 'Item001',
'type': 'RESULT'
},{
'name': 'Item002',
'type': 'OTHER'
},
{
'name': 'Item005',
'type': 'GAME'
},
{
'name': 'Item0039',
'type': 'RESULT'
}
如何按以下順序對 flutter 中的列表進行排序,我想先查看 RESULT 項,然后是 GAME,然后是 OTHER 項。
任何有解決方案的想法的人?
在您使用List<Map<String, String>>
的情況下,您應該實現自己的比較 function。
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);
});
}
如果添加新的不同類型字符串,則必須為比較 function 添加邏輯。 將此代碼放入您的測試文件中,它將打印:
{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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.