【问题标题】:Flutter json map array of obejcts to classFlutter json将对象数组映射到类
【发布时间】:2018-08-15 19:14:32
【问题描述】:

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

将显示以下错误:

类型“MappedListIterable”不是类型“List”的子类型


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,
    );
  }
}

错误

【问题讨论】:

    标签: dart flutter


    【解决方案1】:

    您的代码 perfectly 适合我。

    如果我们在下面的 sn-p 中错过了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>'
    

    【讨论】:

    • 你用的是什么版本的flutter?我使用 0.5.1
    • 和你的一样。 Dart 虚拟机版本:1.24.3
    • class Set {这一行之前,上面的代码中缺少}(看起来设置为内部类)。由于Dart 不允许内部类,它应该是typo
    • 对不起,我会改代码。该模型看起来如此。 gist.github.com/aBuder/ca09a5d08ede710e032f26dbaf45560a
    猜你喜欢
    • 2017-12-24
    • 2020-02-10
    • 1970-01-01
    • 2019-05-27
    • 1970-01-01
    • 2021-08-16
    • 2015-05-16
    • 1970-01-01
    • 2021-11-26
    相关资源
    最近更新 更多