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

Flutter请求NewsAPI解析JSON时出现类型不匹配错误如何解决?

问题排查与修复方案

错误原因

  • 触发_InternalLinkedHashMap<String, dynamic> is not a subtype of type Iterable<dynamic>报错的核心原因:目标NewsAPI返回的根数据为字典(Map)结构,而非可直接遍历的数组,直接对根Map执行for-in遍历会触发类型不匹配异常。
  • 额外隐藏问题:初始化列表时使用List<FetchDataClass>.empty(),该方法默认生成不可增长的固定长度列表,后续执行add、addAll操作会触发异常。

接口结构说明

你调用的https://newsapi.org/v2/everything接口返回的根结构固定为三个字段:

  1. status:请求状态
  2. totalResults:返回的新闻总条数
  3. articles:新闻列表数组,为需要解析的目标数据

修复后的代码

1. 数据拉取逻辑修复

// 初始化改为可增长列表
List<FetchDataClass> listofdata = [];

Future<List<FetchDataClass>> loadNews() async {
  var response = await http.get(Uri.parse('https://newsapi.org/v2/everything?q=coronavirus&from=2021-09-10&sortBy=publishedAt&apiKey=替换为你的APIKEY'));
  // 初始化可增长列表
  List<FetchDataClass> news = [];
  if(response.statusCode == 200) {
    // 明确声明根结构是Map类型
    Map<String, dynamic> responseJson = json.decode(response.body);
    // 取出新闻列表数组,做空值兜底处理
    List<dynamic> articlesJson = responseJson['articles'] ?? [];
    for(dynamic noteJson in articlesJson) {
      news.add(FetchDataClass.fromJson(noteJson));
    }
  }
  return news;
}

@override
void initState() {
  loadNews().then((value) {
    setState(() {
      listofdata.addAll(value);
    });
  });
  super.initState();
}

2. 数据模型类优化(可选,避免空值崩溃)

接口返回的部分字段可能为空,建议将late声明改为可空类型或添加默认值:

class FetchDataClass {
  String? author;
  String? title;
  String? description;
  String? url;
  String? urlToImage;
  String? publishedAt;
  String? content;

  FetchDataClass(this.author, this.title, this.description, this.url, this.urlToImage, this.publishedAt, this.content);
  
  FetchDataClass.fromJson(Map<String, dynamic> jsonData) {
    author = jsonData['author'] ?? '未知作者';
    title = jsonData['title'] ?? '无标题';
    description = jsonData['description'] ?? '无描述';
    url = jsonData['url'] ?? '';
    urlToImage = jsonData['urlToImage'] ?? '';
    publishedAt = jsonData['publishedAt'] ?? '未知时间';
    content = jsonData['content'] ?? '无内容';
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 18:03:02