Home > other >  How to sort TimeOfDay list from earliest to latest time?
How to sort TimeOfDay list from earliest to latest time?

Time:10-11

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

CodePudding user response:

i think you are missing return value form sort method. since you are using curly brackets,

here i try on dartpad is working fine

void main() {
List date = ['2022-02-02','2022-02-15','2022-02-01'];
  
  date.sort((a,b) => DateTime.parse(a).compareTo(DateTime.parse(b)));
  
  print(date); //result : [2022-02-01, 2022-02-02, 2022-02-15]
}

if you have 1 argument, you can simplify with arrow => , but if you have more than 1, use brackets {}

 l.sort((a,b){
     return  DateTime.parse(a).compareTo(DateTime.parse(b)); // see i add a return syntax
    });

CodePudding user response:

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);
}
  • Related