You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中JSON转Map报错:'List'不是'String'的子类型

问题原因

服务器返回的是航线列表(JSON数组),但你在代码里直接将response.body(类型为List)传给了需要单个Map参数的RouteModel.fromJson()方法,导致类型不匹配,抛出'type 'List' is not a subtype of type 'String''错误。

解决方法

修改FlightRouteListController中的getAllFlightRoute方法,遍历返回的List数据,逐个解析为RouteModel对象:

Future<void> getAllFlightRoute()async{
  Response response = await flightRouteListRepository.getAllRouteList();
  try{
    _isLoaded = true;
    update();
    if(response.statusCode==200){
      print("Got route from the server");
      _routeModelList = [];
      // 遍历服务器返回的列表,逐个解析为RouteModel
      if(response.body is List){
        for(var item in response.body){
          _routeModelList.add(RouteModel.fromJson(item));
        }
      }
      print(_routeModelList);
    }else{
      print("The response code is: "+response.statusCode.toString());
      print("The error is: "+response.statusText!);
    }
  }catch(e){
    print(e.toString());
  }
  _isLoaded =false;
  update();
}
额外建议
  • 给RouteModel的字段添加空值兜底逻辑,比如用json['takeOffLocation'] ?? ''避免空值引发的潜在问题
  • 如果API返回的结构是外层包裹了列表(比如{"data": [/* 航线列表 */]}),需要先提取对应字段再遍历,比如response.body['data']

内容的提问来源于stack exchange,提问作者Ukeme Elijah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 15:09:58