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

Flutter API请求报错:type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'FutureOr<List<Attributes>>'

解决Flutter中type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'FutureOr<List<Attributes>>'错误

这个错误的核心问题在于你误解了API返回的JSON结构,以及后续的类型转换逻辑错误。让我一步步帮你排查和解决:

错误原因分析

你的API返回的JSON根结构是一个对象(Map),而不是直接的数组(List)。但你在修改后的代码里尝试把整个Map强制转换为List,这必然会触发类型不匹配的错误——因为_InternalLinkedHashMap(Flutter中Map的默认实现)根本不可能转成List类型。

解决步骤

1. 明确API返回的JSON结构

首先你需要确认API返回的具体格式,这类嵌套API通常会返回类似这样的结构:

{
  "data": [
    {
      "name": "示例分类名称",
      "image": {"url": "https://example.com/category.jpg"}
    },
    // 更多分类条目...
  ]
}

核心要点:列表数据嵌套在根对象的某个字段里(比如data),而不是根节点直接是数组。

2. 修正API调用方法

你需要先从根Map中提取出对应的列表字段,再逐个转换为Attributes对象。修改后的getPosts方法如下:

Future<List<Attributes>> getPosts() async {
  var response = await http.get(Uri.parse(get_categ));
  if (response.statusCode == 200) {
    // 解析根响应为Map类型
    var jsonResponse = json.decode(response.body) as Map<String, dynamic>;
    
    // 替换成你API中实际存储列表的字段名,比如"data"、"categories"等
    var attributesJsonList = jsonResponse["data"] as List; 
    
    // 将列表中的每个JSON对象转换为Attributes实例
    return attributesJsonList.map((attrJson) => Attributes.fromJson(attrJson)).toList();
  } else {
    throw Exception('Failed to load data: ${response.statusCode}');
  }
}

3. 补全嵌套模型类的实现

你提到了嵌套JSON,所以Image类也需要完整的fromJson解析逻辑(你之前没提供,这里补充一个示例,根据你的API实际字段调整):

class Image {
  final String? url;
  // 可根据API返回的字段添加更多属性,比如width、height等

  Image({this.url});

  factory Image.fromJson(Map<String, dynamic> json) {
    return Image(
      url: json["url"], // 替换成API中Image对象的实际字段名
    );
  }
}

4. 规范initState的调用顺序

另外,Flutter中initState方法里应该先调用super.initState(),这是官方推荐的最佳实践,避免状态初始化异常:

@override
void initState() {
  super.initState(); // 优先调用父类初始化方法
  loadCategories();
}

// 单独抽离异步逻辑,让代码更清晰易维护
void loadCategories() async {
  try {
    List<Attributes> categories = await getPosts();
    print("Loaded ${categories.length} categories");
    print("First category name: ${categories.first.name}");
  } catch (e) {
    print("Error loading categories: $e");
  }
}

关键提醒

  • 一定要根据你实际API返回的JSON结构,修改jsonResponse["data"]中的字段名——如果你的API列表字段是attributes,就改成jsonResponse["attributes"]。
  • 如果API返回的根节点确实是数组(直接是[...]),那你可以直接把json.decode(response.body)转成List,但根据错误信息来看,你的情况显然不是这种。

内容的提问来源于stack exchange,提问作者Ibrahim Mahmoud

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 23:02:27