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

Time:05-26

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

CodePudding user response:

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.

CodePudding user response:

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!

CodePudding user response:

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}]
  • Related