简体   繁体   中英

What is the Javascript “map” equivalent in Dart?

I'm new to Dart and I noticed that the method map is not working the same as in Javascript.

I'm trying to convert a list of dynamic to a list of object.

In Javascript, this would work:

List<BoxType> boxTypes = data["boxTypes"].map((dynamic boxType) => BoxType.fromDynamic(boxType));

But in Dart, I got this error:

Exception has occurred.
_TypeError (type 'MappedListIterable<dynamic, dynamic>' is not a subtype of type 'List<BoxType>')

I saw that I could do a .toList() at the end like this:

List<BoxType> boxTypes = data["boxTypes"].map((dynamic boxType) => BoxType.fromDynamic(boxType)).toList();

But it generates this error:

Exception has occurred.
_TypeError (type 'List<dynamic>' is not a subtype of type 'List<BoxType>')

So, what should I use instead of map ?

Edit: For now, that's what I'm doing, it's a bit ugly but it works well

for (var i = 0; i < data["boxTypes"].length; i++) {
  boxTypes.add(BoxType.fromDynamic(data["boxTypes"][i]));
}

因为你在map使用dynamic而不是BoxType - 错误说'List<dynamic>' is not a subtype of 'List<BoxType>' ,所以修复它应该有效:

List<BoxType> boxTypes = data["boxTypes"].map((BoxType boxType) => BoxType.fromDynamic(boxType)).toList();

This code runs without problems:

void main() {
  List dynamicList = [1, 2, "hello", true];

  Map<String, List> map = {'boxTypes': dynamicList};

  // make sure to check for null with ?. and reeturn an empty list if null
  List<BoxType> boxes = map["boxTypes"]?.map((box) => BoxType.fromDynamic(box))?.toList() ?? [];

  // same, but a little shorter
  //List<BoxType> boxes = map["boxTypes"]?.map(BoxType.fromDynamic)?.toList() ?? [];


  print(boxes);
}

class BoxType {
  String type;
  BoxType(this.type);

  static BoxType fromDynamic(value) {
    if (value is String) {
      return BoxType(value);
    }
    return BoxType(value?.toString() ?? "no value");
  }

  String toString() => "BoxType{type=${type}}";
}

If I change the type of map to Map<String, dynamic> , however, I get the same error as you...

Can you verify the type of your map declares the values as being List ?

The Dart compiler should pick this up as a type-checking error, but that doesn't seem to be happening until runtime.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM