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

Flutter解析FastAPI返回JSON时类型不匹配问题求助

问题:从FastAPI获取数据绑定卡片视图时的类型不匹配错误

出现的错误

// 未应用toList()时:
type 'MappedListIterable<dynamic, dynamic>' is not a subtype of type 'List<Place>' 

// 应用toList()时:  
type 'List<dynamic>' is not a subtype of type 'bool' 

FastAPI返回的JSON数据

{
    "status_code": 200, 
    "status_msg": "ok", 
    "data": [{
            "id": 12, 
            "name": "name1", 
            "images": ["img1.jpg", "img2.jpg", "img3.jpg"], 
            "description": "description1", 
            "location": "address1",  
            "likes": 16700, 
            "comments": 10  
        }, 
        {
            "id": 13, 
            "name": "name2", 
            "images": ["img4.jpg", "img5.jpg", "img6.jpg"], 
            "description": "description1", 
            "location": "address1",  
            "likes": 190002, 
            "comments": 9  
        } 
    ] 
}

Place模型类代码

class Place {
  int? id;
  String? name;
  List<String>? images;
  String? description;
  String? location;  
  int? likes;
  int? comments; 

  Place(
      {this.id,
      this.name,
      this.images,
      this.description,
      this.location, 
      this.likes,
      this.comments });

  factory Place.fromJson(Map<String, dynamic> json) {
    return Place(
        id: json['id'] ?? '',
        name: json['name'] ?? '',
        images: json['images'] ? null : json['images'],
        description: json['description'] ?? '',  
        likes: json['likes'],
        comments: json['comments']); 
  }
} 

Flutter API数据处理代码

Future getData() async {
    List<Place> _data = [];
    List<Place> get data => _data;

    SharedPreferences sp = await SharedPreferences.getInstance();
    String? uid = sp.getString('uid');
    if (uid == null) uid = 'system'; 
    final params = <String, dynamic>{
      'uid': uid,
      'curr_loc': '',
      'flag': 'P',
      'top_k': 5
    };

    final _resp = await dio.get(
      Config().baseAPIURL + '/api_name',
      queryParameters: params,
      options: Options(
        headers: {
          "authorization": Config().APIToken,
        },
      ),
    );

    if (_resp.data["status_code"] == 200) {
      _data = _resp.data["data"].map((x) => Place.fromJson(x)).toList(); // <--- 错误发生在此处 
    } else {}
    notifyListeners();
  } 

修复方案

1. 修正Place模型的fromJson方法

模型里有两处错误直接导致类型不匹配:

  • id字段:json['id'] ?? '' 中,''是字符串类型,但id定义为int?,类型不兼容。如果API返回的id不会为null,直接写id: json['id'];如果需要默认值,用id: json['id'] ?? 0
  • images字段:json['images'] ? null : json['images'] 逻辑完全颠倒,而且直接赋值会得到List<dynamic>,无法匹配List<String>?的类型要求。需要转换成指定类型,修改为:
    images: json['images'] == null ? null : List<String>.from(json['images']),
    

修正后的fromJson方法:

factory Place.fromJson(Map<String, dynamic> json) {
  return Place(
      id: json['id'],
      name: json['name'] ?? '',
      images: json['images'] == null ? null : List<String>.from(json['images']),
      description: json['description'] ?? '',  
      likes: json['likes'],
      comments: json['comments']); 
}

2. 明确数据转换的泛型类型

在处理API返回数据时,给map方法指定泛型,确保转换后的列表严格为List<Place>:

_data = _resp.data["data"].map<Place>((x) => Place.fromJson(x)).toList();

或者用另一种写法:

_data = List<Place>.from(_resp.data["data"].map((x) => Place.fromJson(x)));

完成以上修改后,就能解决类型不匹配问题,确保API返回的动态数据正确转换成List<Place>类型,正常绑定到卡片视图。


内容的提问来源于stack exchange,提问作者Chris Joo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 03:39:56