Flutter filter list based on last week, last month and last year

Viewed 5750

I have list of map where there is a date field. In the screen I have filter option where I can filter data based on last week, last month and last year so Don't know how can achieve the result.

Below is my code

 _listOfHistory.addAll(
         _listStaticRoundForHistory.
         where((element) {
           final date = element.date;
           return date == date.subtract(Duration(days: 30));
         }
     ).toList());

But pretty sure that wrong.

Response Listing

[
 {
   "title": "title",
   "details": "details",
   "date": DateTime
 },
 {
   "title": "title",
   "details": "details",
   "date": DateTime
 }
 .
 .
 .
 .
]
1 Answers

where I can filter data based on last week, last month and last year

First you need to know which day is today, in order to subtract days, months or years.

var now = new DateTime.now();
var now_1w = now.subtract(Duration(days: 7)); 
var now_1m = new DateTime(now.year, now.month-1, now.day);
var now_1y = new DateTime(now.year-1, now.month, now.day);

EDIT Then in your code you just need to evaluate if now is after any of the dates you are creating above, for example for 1 week:

where((element) {
           final date = element.date;
           return now_1w.isBefore(date);
         }
Related