Kagimura
Kagimura

Reputation: 417

Converting a List of DateTime into Strings

I'm trying to covert a list of dates into a string

    var list = <DateTime>[];
    DateTime start = DateTime(2019, 12, 01);
    final end = DateTime(2021, 12, 31);

    while (start.isBefore(end)) {
      list.add(start);
      start = start.add(const Duration(days: 1));
    }

    list.map((DateTime time) {
      var dateRange = DateFormat("MM-dd-yy").format(time);
      List<String> userSearchItems = [];

      userSearchItems.add(dateRange);

      print(userSearchItems);
    });

but userSearchItems is coming up as empty

Upvotes: 0

Views: 287

Answers (1)

Lesiak
Lesiak

Reputation: 26079

The code block inside list.map is never executed.

This is because list.map produces a lazy transformation of the list. The transformation function is executed only when elements are requested from it.

You probably want to use:

var dates = list.map((DateTime time) {
      var dateRange = DateFormat("MM-dd-yy").format(time);
      return dateRange;
});
print(dates);

In the code above, it is the print function that forces the transformation to run.

Alternatively, you can transform the result of the list.map to a list using

var datesList = dates.toList();

Again, this forces eager evaluation of the map transformation.

Upvotes: 1

Related Questions