'`,arrays,list,flutter"/>

首页 > 解决方案 > Flutter mapping json to model array 'List' is not a subtype of type 'Map'`

问题描述

I am reading a json with few different arrays. So I want to map it to its individual model list. Thus first I created the list for e.g. as below.

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'],

    );
  }
}

I have managed to call my api and below is how my json results look like its not the complete one as I wanted to make it brief.

"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": [
          ..........
        ]

Below is how I wrote to populate the summary array.

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

I end up getting type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>'

标签: arrayslistflutter

解决方案


这是因为返回的响应包含 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]));

推荐阅读