I have the following function that sort List based on Date but if DateTime before firstDay of month it create double list
what I want is it sort list based on first day of month and remove all item before firstday
List expenseData= [
{id: 1242, detail: milk, amount: $5, date: 2021-06-21 00:00:00:000},
{id: 1242, detail: egg, amount: $2, date: 2021-05-15 00:00:00:000},
{id: 1243, detail: bread, amount: $3, date: 2021-05-13 00:00:00:000},
{id: 1244, detail: butter, amount: $7, date: 2021-05-22 00:00:00:000},
{id: 1247, detail: butter, amount: $7, date: 2021-06-10 00:00:00:000},
];
pieDatathisMonth() {
var now = DateTime.now();
var firstDayMonth = DateTime(now.year, now.month, 1);
var sortExpData = expenseData;
sortExpData.sort((d1, d2) {
return d1.date.compareTo(firstDayMonth);
});
sortExpData.toList();
thisMonthExpense.addAll(sortExpData);
update();
}
sortcallback is wrong. It must compared1tod2, notd1to some other date. Otherwisesort()cannot properly orderd1relative tod2. If you want to remove all dates before a cut-off date, it'd be better to filter your list withexpenseData.where((dateTime) => dateTime.compareTo(firstDayOfMonth) >= 0)and then sort it.