如何在地图列表中将时间排序为字符串 - Dart/Flutter

How to Sort time as String inside a List of Maps - Dart/Flutter

地图列表:

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

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)}";
  }
}

我们需要从地图创建对象,然后将时间转换为日期时间。然后需要覆盖 toString 方法以获得所需的输出。

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']));
    });

享受编码!

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}]
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("------------------");
  });
}