【问题标题】:Flutter mapping json to model array 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>'`Flutter 将 json 映射到模型数组“List<dynamic>”不是“Map<String, dynamic>”类型的子类型
【发布时间】:2019-08-01 03:19:59
【问题描述】:

我正在阅读一个包含几个不同数组的 json。所以我想将它映射到它的单个模型列表。因此,首先我为例如创建了列表如下。

class Summary {


  final String totalDuration;
  final String totalMileage;
  //final String fleetID;

  Summary({this.totalDuration, this.totalMileage});

  Map<String, dynamic> toJson() => {
        'totalDuration': totalDuration,
        'totalMileage': totalMileage,

      };

  factory Summary.fromJson(Map<String, dynamic> json) {
    return new Summary(
      totalDuration: json['totalDuration'],
      totalMileage: json['totalMileage'],

    );
  }
}

我已经成功调用了我的 api,下面是我的 json 结果看起来不是完整的结果,因为我想让它简短。

"totalSummary": 6,
    "Summary": [
        {
            "totalDuration": "2549",            
            "totalMileage": "22.898"
        },
        { 
            "totalDuration": "11775",
            "totalMileage": "196.102"
        },
        {
            "totalDuration": "17107",
            "totalMileage": "232.100"
        },
        {  
            "totalDuration": "34870",
            "totalMileage": "177.100"
        },
        {
            "totalDuration": "33391",
             "totalMileage": "168.102"
        },
        {
            "totalDuration": "13886",
            "totalMileage": "77.398"
        }
    ],
    "totalDetails": 16,
    "details": [
          ..........
        ]

下面是我编写的填充汇总数组的方法。

final fullJson = await NetworkUtils.post(url,token,data);
        print("fullJson"+fullJson.toString());
        try{
        Summary summary1 = new Summary.fromJson(fullJson['Summary']);

         print(summary1.totalMileage);
        }
        catch(Err){
          print("Erro is at"+Err.toString());
        }

我最终得到type 'List&lt;dynamic&gt;' is not a subtype of type 'Map&lt;String, dynamic&gt;'

【问题讨论】:

    标签: arrays list flutter


    【解决方案1】:

    这是因为返回的响应包含 Map List 而不是 map 。

    换行Summary summary1 = new Summary.fromJson(fullJson['Summary']);

    Summary summary1 = new Summary.fromJson(fullJson['Summary'][i]);

    其中 i 可以是 0 到 Summary 中的对象数减一之间的任何值。

    要获取Summary 对象的完整列表,请执行以下操作:

    int totalSummaryCount = fullJson['totalSummary'];
    List<Summary> list = new List<Summary>.generate(totalSummaryCount, (index)=>Summary.fromJson(fullJson['Summary'][index]));
    

    【讨论】:

    • 如何一次性完成整个列表而不是一个一个?
    • 好的,我会试试的。所以当我回忆起api时我需要先清除以前的 List
    • 什么是完全清除任何 List 等的正确命令意味着在每个 api 之后我根本不想要任何旧值
    • 您可以在收到来自 API 的响应时使用list.clear();,或者您可以创建一个类变量并使用获得的结果更新它。可以看官方List文档here
    • 如何清除我们定义为 List list = new List 的原因?
    猜你喜欢
    • 2023-01-07
    • 2019-08-18
    • 2021-06-09
    • 2021-12-02
    • 2020-11-12
    • 2021-12-29
    • 2023-01-08
    • 2021-07-11
    • 2021-04-06
    相关资源
    最近更新 更多