Home > Software design >  How to cast from List<dynamic> to List<DateTime> in Dart/Flutter?
How to cast from List<dynamic> to List<DateTime> in Dart/Flutter?

Time:09-29

I'm trying to convert a List<dynamic> to List<DateTime>.

I have this:

factory PredSche.fromJson(Map<String, dynamic> parsedJson) {
    print(parsedJson); //{values: [2021-09-06T11:00:00.000Z, 2021-09-08T13:00:00.000Z, 2021-09-07T11:00:00.000Z], name: first}

    var list = parsedJson['values'];
    print(list); //[2021-09-06T11:00:00.000Z, 2021-09-08T13:00:00.000Z, 2021-09-07T11:00:00.000Z]
    print(list.runtimeType); //List<dynamic>

    var listDates = list.map((date) => DateTime.parse(date)).toList();
    print(listDates[0].runtimeType); //DateTime
    print(listDates.runtimeType); //List<dynamic>

    return new PredSche(
        name: parsedJson['name'],
        values: listDates);
}

What I'm doing wrong?

CodePudding user response:

You're letting dart infer the type of listDates and that together with simply calling toList() makes dart infer dynamic as a type argument for the variable listDates. To solve this you can replace var listDates = list.map((date) => DateTime.parse(date)).toList(); with List<DateTime> listDates = List<DateTime>.from(list.map((date) => DateTime.parse(date)));, which should output this:

List<String>
DateTime
List<DateTime>
  • Related