地图列表:
void main() {
List place = [
{"place": "India", "time": "10:30"},
{"place": "China", "time": "5:10"},
{"place": "Nepal", "time": "11:00"},
{"place": "Pakistan", "time": "4:30"},
];
}
期望输出值:
巴基斯坦:4.30
中国:5.10
印度:10.30
尼泊尔:11.0
void main() {
List place = [
{"place": "India", "time": "10:30:00"},
{"place": "China", "time": "05:10:00"},
{"place": "Nepal", "time": "11:00:00"},
{"place": "Pakistan", "time": "04:30:00"},
];
place.sort((a, b) => DateTime.parse("2022-02-20 " + a['time']).compareTo(DateTime.parse("2022-02-20 " + b['time'])));
print(place.toString());
}
打印结果:
[{place: Pakistan, time: 04:30:00}, {place: China, time: 05:10:00}, {place: India, time: 10:30:00}, {place: Nepal, time: 11:00:00}]
1 -在pubspec.yml
中添加依赖
intl: ^0.17.0
2 -添加时间转换方法
int convertTime(String timeStr){
final format = DateFormat('HH:mm');
final dt = format.parse(timeStr, true);
return dt.millisecondsSinceEpoch;
}
3 -使用下面的代码过滤器。
place.sort((a, b) {
return convertTime(a['time']).compareTo(convertTime(b['time']));
});
享受鳕鱼!
import 'package:intl/intl.dart';
void main(){
List<Map<String, String>> place = [
{"place": "India", "time": "10:30"},
{"place": "China", "time": "05:10"},
{"place": "Nepal", "time": "11:00"},
{"place": "Pakistan", "time": "04:30"},
];
var a = place.map((Map<String, String> e) {
return Place.fromJson(e);
}).toList();
a.sort((a, b) => a.time.compareTo(b.time));
for(var e in a){
print(e);
}
}
class Place {
Place({required this.name, required this.time});
final String name;
final DateTime time;
factory Place.fromJson(Map<String, String> json) {
return Place(
name: json['place']!,
time: DateTime.parse('2020-01-02T${json['time']!}'),
);
}
Map<String,dynamic> toJson() => {
'name': name,
'time': time,
};
@override
String toString() {
return "$name ${DateFormat("HH:mm").format(time)}";
}
}
我们需要从map创建对象,然后将time转换为datetime。然后需要重写toString方法来获得所需的输出。
void main() {
List place = [
{"place": "India", "time": "10.30"},
{"place": "China", "time": "5.10"},
{"place": "Nepal", "time": "11.00"},
{"place": "Pakistan", "time": "4.30"},
];
var x = place..sort(
(a, b) => double.parse(a["time"]).compareTo(double.parse(b["time"])));
x.forEach((value) {
print("Place : ${value["place"]}");
print("Time : ${value["time"]}");
print("------------------");
});
}