Flutter JSON对象映射到类的数组

时间:2018-08-15 19:14:33

标签: dart flutter

我想将以下json结构映射到模型。我尝试将数组映射到List,然后解析每个模型集。

将显示以下错误:

“ MappedListIterable”类型不是“列表”类型的子类型


Json

  {
      "objectId": "vbbZIPV6qs",
      "sets": [
        {
          "repetitions": 10,
          "weight": 10,
          "time": 0
        }
      ],
      "description": "",
      "type": "EXERCISE",
    }

颤振

class PlanItem {
  String type;
  String description;
  List<Set> sets = [];

  PlanItem(this.type, this.description, this.sets);

  factory PlanItem.fromJson(Map<String, dynamic> json) {
    return PlanItem(
      json['type'],
      json['description'],
      (json['sets'] as List).map((i) {
        return Set.fromJson(i);
      }).toList(),
    );
  }
}

class Set {
  int repetitions;
  int weight;
  int time;

  Set(this.repetitions, this.weight, this.time);

  // convert Json to an exercise object
  factory Set.fromJson(Map<String, dynamic> json) {
    return Set(
      json['repetitions'] as int,
      json['weight'] as int,
      json['time'] as int,
    );
  }
}

错误 enter image description here

1 个答案:

答案 0 :(得分:2)

您的代码perfectly对我有用。

如果我们在下面的代码段中错过了toList(),我们将收到此错误,

(json['sets'] as List).map((i) {
    return Set.fromJson(i);
  }).toList(), // removing toList will get below error
// type 'MappedListIterable<Map<String, int>, Set>' is not a subtype of type 'List<Set>'