简体   繁体   中英

Flutter - Dart: Sort a List that includes lists of doubles and DateTime, by dateTime

This is my List:

myList = [[0.0, 3 Jan 2023], [0.0, 7 Jan 2023], [139.36986081071, 1 Jan 2023], [139.84969328013125, 11 Jan 2023], [97.84468694063244, 11 Jan 2023]];

I would like to sort that list not by the double number but by dateTime, the earlier date first. Of course I don't want the lists inside the List to brake.

Any help appreciate it:)

Thanks!

You can use List.sort() with DateTime.compareTo() :

myList.sort((a, b) => a[1].compareTo(b[1]));

Using your example data:

var myList = <List<dynamic>>[
  [0.0, DateTime(2023, 01, 03)], 
  [0.0, DateTime(2023, 01, 07)], 
  [139.36986081071, DateTime(2023, 01, 01)], 
  [139.84969328013125, DateTime(2023, 01, 11)], 
  [97.84468694063244, DateTime(2023, 01, 11)]
]; 

main() {
  myList.sort((a, b) => a[1].compareTo(b[1]));
  print(myList);
}

The output is:

[[139.36986081071, 2023-01-01 00:00:00.000], [0, 2023-01-03 00:00:00.000], [0, 2023-01-07 00:00:00.000], [139.84969328013125, 2023-01-11 00:00:00.000], [97.84468694063244, 2023-01-11 00:00:00.000]]

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