gpt4 book ai didi

arrays - 如何在Dart中对该数组/映射进行排序?

转载 作者:行者123 更新时间:2023-12-03 04:27:29 25 4
gpt4 key购买 nike

如何从Dart中的“数据”对 map /数组进行排序?

var training = [
{"data" : "15/10/2019" , "pic" : "assets/images/foto3.jpg"},
{"data" : "10/10/2019" , "pic" : "assets/images/foto5.jpg"},
{"data" : "15/10/2019" , "pic" : "assets/images/foto4.jpg"},
{"data" : "30/10/2019" , "pic" : "assets/images/bocateam.jpg"},
{"data" : "17/10/2019" , "pic" : "assets/images/foto2.jpg"},
];

最佳答案

我不确定您要排序的内容,但我会根据“数据”值猜测是按日期排序。请看一下此实现,并告诉我是否有您不了解的内容:

void main() {
final training = [
{"data": "15/10/2019", "pic": "assets/images/foto3.jpg"},
{"data": "10/10/2019", "pic": "assets/images/foto5.jpg"},
{"data": "15/10/2019", "pic": "assets/images/foto4.jpg"},
{"data": "30/10/2019", "pic": "assets/images/bocateam.jpg"},
{"data": "17/10/2019", "pic": "assets/images/foto2.jpg"},
];

training.sort((map1, map2) {
final date1 = parseDate(map1['data']);
final date2 = parseDate(map2['data']);
return date1.compareTo(date2);
});

training.forEach(print);
// {data: 10/10/2019, pic: assets/images/foto5.jpg}
// {data: 15/10/2019, pic: assets/images/foto3.jpg}
// {data: 15/10/2019, pic: assets/images/foto4.jpg}
// {data: 17/10/2019, pic: assets/images/foto2.jpg}
// {data: 30/10/2019, pic: assets/images/bocateam.jpg}
}

// Format: 15/10/2019
DateTime parseDate(String date) {
final parts = date.split('/');
return DateTime(
int.parse(parts[2]), int.parse(parts[1]), int.parse(parts[0]));
}

如果每个日期都首先转换为 DateTime对象,则实现可能会更高效,因此我们在排序时不需要多次转换每个对象。但是,如果 list 很短,那不是主要问题。

关于arrays - 如何在Dart中对该数组/映射进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58632008/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com