0

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!');
  }
nsa41620
  • 13
  • 4

2 Answers2

1

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
    });
pmatatias
  • 3,491
  • 3
  • 10
  • 30
1

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);
}
jamesdlin
  • 81,374
  • 13
  • 159
  • 204
  • How does list.sort(compareTimeOfDay); work? Because compareTimeOfDay takes in two arguments – nsa41620 Oct 11 '22 at 23:30
  • @nsa41620 The callback to [`List.sort`](https://api.dart.dev/stable/dart-core/List/sort.html) is supposed to take exactly two arguments. You yourself passed a callback that takes two arguments in the code that you tried. – jamesdlin Oct 12 '22 at 02:51
  • My list has more than two arguments so how would I pass all of them through? – nsa41620 Oct 12 '22 at 14:13
  • @nsa41620 Do you mean more than two *elements*? The `List` in the example I've shown has more than two elements too. A sorting algorithm compares two elements at a time. – jamesdlin Oct 12 '22 at 15:19