Home > front end >  Flutter filter list by dates
Flutter filter list by dates

Time:11-21

So I am getting a Promo List from an API that has a dateStart and dateEnd field which returns YYYY-MM-DD String or null if it is empty. Now I want to compare/filter.

1- has dateStart=YYYY-MM-DD && has dateEnd=YYYY-MM-DD - is ok to render but if dateEnd == today or over then it wont show

2- has dateStart=YYYY-MM-DD && has dateEnd=null - is ok to render in the list as it may be a lifetime promo

3- only show in list if dateStart is today or has already passed

CodePudding user response:

Lets assume this is your list:

List sampleList = [
    {"dateStart": "2022-11-18", "dateEnd": "2022-11-22"},
    {"dateStart": "2022-11-20", "dateEnd": "2022-11-20"},
    {"dateStart": "2022-10-20", "dateEnd": "2022-11-19"},
    {"dateStart": "2022-10-20", "dateEnd": null},
  ];

so you can get your list like this:

var result = sampleList.map((e) {
      if (e['dateStart'] != null) {
        DateTime startDate =
            DateFormat("yyyy-MM-dd").parse(e['dateStart']   ' 23:59');
        DateTime? endDate = e['dateEnd'] != null
            ? DateFormat("yyyy-MM-dd hh:mm").parse(e['dateEnd']   ' 23:59')
            : null;
        var now = DateTime.now();

        if ((startDate.isBefore(now) || startDate == now) &&
            (endDate == null || endDate.isBefore(now))) {
          return e;
        }
      }
    }).toList();
result.removeWhere((element) => element == null);

print("result = $result");//result = [{dateStart: 2022-10-20, dateEnd: 2022-11-19}, {dateStart: 2022-10-20, dateEnd: null}]

now you can use result to show your list.

  • Related