fluttertimeofday

How to sort TimeOfDay list from earliest to latest time?


I need to display a schedule for users that displays times from earliest to latest time. I have a TimeOfDay list containing times and need it to be sorted from earliest to latest time. I made a function for it, but keep getting _TypeError (type 'TimeOfDay' is not a subtype of type 'String') when I run my code. Since I utilize the function inside a Column in my Widget build code block, I think it has to return a widget. Please let me know how I can resolve this error and efficiently sort my list through a function. The code for my function is below, any help would be appreciated!

  listOrder(l) {
    l.sort((a,b) => DateTime.parse(a).compareTo(DateTime.parse(b)));
    return Text('Done!');
  }

Solution

  • DateTime.parse expects a String input, not a TimeOfDay instance.

    If you want to sort a List<TimeOfDay>, you need to provide a comparison function that compares TimeOfDay instances:

    int compareTimeOfDay(TimeOfDay time1, TimeOfDay time2) {
      var totalMinutes1 = time1.hour * 60 + time1.minute;
      var totalMinutes2 = time2.hour * 60 + time2.minute;
      return totalMinutes1.compareTo(totalMinutes2);
    }
    
    void main() {
      var list = [
        TimeOfDay(hour: 12, minute: 59),
        TimeOfDay(hour: 2, minute: 3),
        TimeOfDay(hour: 22, minute: 10),
        TimeOfDay(hour: 9, minute: 30),
      ];
    
      list.sort(compareTimeOfDay);
      print(list);
    }