0

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();
  }
3
  • what's the error? Commented Jun 28, 2021 at 6:17
  • 1
    Your sort callback is wrong. It must compare d1 to d2, not d1 to some other date. Otherwise sort() cannot properly order d1 relative to d2. If you want to remove all dates before a cut-off date, it'd be better to filter your list with expenseData.where((dateTime) => dateTime.compareTo(firstDayOfMonth) >= 0) and then sort it. Commented Jun 28, 2021 at 6:37
  • nothing error showed because the problem is my filtering I see it thanks for your clue Commented Jun 28, 2021 at 9:38

1 Answer 1

1

Here is a fix to your sort method. I've made some DateTime cast because my expenseData is formatted as Map<String, dynamic>.

void pieDatathisMonth() {
  var now = DateTime.now();
  var firstDayMonth = DateTime(now.year, now.month, 1);
  var sortExpData = List<Map<String, dynamic>>.from(expenseData);
  
  // remove all data before firstday because you don't need to sort them.
  sortExpData.removeWhere((e) => (e['date'] as DateTime).isBefore(firstDayMonth));
  
  sortExpData.sort((d1, d2) {
    return (d1['date'] as DateTime).compareTo(d2['date'] as DateTime);
  });
  sortExpData.toList();
  thisMonthExpense.addAll(sortExpData);
  update();
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.