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

Flutter解析API数据时遇类型不匹配错误,求解决方案

问题分析与解决

你的两个错误本质上指向同一个核心问题:API返回的JSON不是直接的数组,而是一个包含数组的对象。

第一个错误type '(dynamic) => Category' is not a subtype of type '(String, dynamic) => MapEntry<dynamic, dynamic>' of 'transform',是因为你在一个Map(JSON对象)上调用了map方法,而Map.map要求转换函数返回MapEntry,但你传入的是返回Category的函数,类型不匹配。

第二个错误type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Iterable<dynamic>',直接证实了json.decode(str)解析后得到的是Map对象,而非你预期的数组(Iterable类型)。

解决方案

步骤1:确认API返回的JSON结构

先打印categoryResponse.bodyString查看实际返回内容,大概率是类似这样的嵌套结构:

{
  "code": 200,
  "data": [
    {"id": 1, "name": "小说", "icon": "book.png"},
    {"id": 2, "name": "科技", "icon": "tech.png"}
  ]
}

核心特征是分类数组被包裹在某个键(比如data)下面。

步骤2:调整模型解析逻辑

根据API返回的结构,修改解析逻辑以正确提取数组部分:

方式一:直接修改现有解析函数

如果确定外层对象的数组键是data,可以直接修改categoryFromJson:

List<Category> categoryFromJson(String str) {
  final decoded = json.decode(str);
  // 替换成你实际API返回的数组键名,比如data、categories等
  final categoryArray = decoded['data'] as List<dynamic>;
  return List<Category>.from(categoryArray.map((x) => Category.fromJson(x)));
}

方式二:创建统一响应模型(更规范)

如果你的API有统一的响应格式,建议创建专门的响应类来适配:

class CategoryApiResponse {
  final int code;
  final List<Category> data;

  CategoryApiResponse({required this.code, required this.data});

  factory CategoryApiResponse.fromJson(Map<String, dynamic> json) {
    var dataList = json['data'] as List;
    List<Category> categoryList = dataList.map((item) => Category.fromJson(item)).toList();
    return CategoryApiResponse(
      code: json['code'],
      data: categoryList,
    );
  }
}

然后在Controller中修改调用逻辑:

if (categoryResponse.statusCode == 200) {
  final apiResponse = CategoryApiResponse.fromJson(json.decode(categoryResponse.bodyString ?? ''));
  categoryList.assignAll(apiResponse.data);
}

步骤3:验证与排查

修改后重新测试,若仍有错误,检查以下两点:

  • API返回的数组键名是否和代码中使用的一致(比如是data还是categories)
  • 数组中每个对象的字段是否与Category.fromJson中的字段完全匹配(比如id是否为int类型、字段名是否拼写错误)

内容的提问来源于stack exchange,提问作者Kennedy Owusu

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 11:25:37