how can I sort list items in flutter/dart based on dateTIme and TimeOfDay?

Issue

I’m making a Todo app, so I want to sort list of tasks based on date and time chosen by user,
currently I’m soring like this, but its not accurate all the time, any other suggestions??

class TaskModel { //model of task
final String? id;
final String? title;
final DateTime? date;
final String? field;
final TimeOfDay? time;
bool isFinished;
TaskModel({
@required this.date,
@required this.id,
@required this.title,
@required this.time,
this.field = 'other',
this.isFinished = false,
});
//method right now I'm using to compare(not efficient)
_tasks.sort((a, b) => a.date!.compareTo(b.date!));
_tasks.sort((a, b) => a.time!.hour.compareTo(b.time!.hour));
_tasks.sort((a, b) => a.time!.minute.compareTo(b.time!.minute));

Solution

use this:

YOURLIST.sort((a, b)=> a.microsecondsSinceEpoch.compareTo(b.microsecondsSinceEpoch));

you can parse DateTime from date and time that users select as follow:

DateTime testDate = DateTime.parse("2021-08-01 20:18:04");
print(testDate.millisecondsSinceEpoch);

so you can replace 2021-08-01 20:18:04 with selectedDate selectedTime

Answered By – Abbasihsn

Answer Checked By – Gilberto Lyons (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *