简体   繁体   中英

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

List of Maps:

void main() {
  List place = [
    {"place": "India", "time": "10:30"},
    {"place": "China", "time": "5:10"},
    {"place": "Nepal", "time": "11:00"},
    {"place": "Pakistan", "time": "4:30"},
  ];
}

Desired Output:

Pakistan: 4.30

China: 5.10

India: 10.30

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

We need to create object from map, then convert time into datetime. Then need to override toString method to get the required output.

1 - Add depedency in pubspec.yml

intl: ^0.17.0

2 - Add this method for time convert

int convertTime(String timeStr){
    final format = DateFormat('HH:mm');
    final dt = format.parse(timeStr, true);
    return dt.millisecondsSinceEpoch;
  }

3 - Use below code for filter.

place.sort((a, b) {
      return convertTime(a['time']).compareTo(convertTime(b['time']));
    });

Enjoy Codding!

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

Print result:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM