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

Flutter调用Quiz API获取question字段抛出NoSuchMethodError问题求助

问题原因

你错误遍历了API返回的最外层Map结构:最外层Map包含response_code和results两个key,第一个keyresponse_code对应的value是int类型的0,当你执行extractedData.forEach遍历到该字段时,尝试对int类型的0调用["question"]取属性,就触发了报错信息中的「int类没有实例方法[]」的错误。

修复方案

你需要的题目数据全部存储在最外层Map的results字段对应的数组里,直接取出该数组遍历即可,不需要遍历整个外层Map,修复后代码如下:

Future<void> showQuestions() async {
  try {
    final response = await http
        .get(Uri.parse('https://opentdb.com/api.php?amount=2'));
    final extractedData = json.decode(response.body) as Map<String, dynamic>;
    // 取出题目数组后遍历,?? [] 做兼容空值处理
    final List questionList = extractedData['results'] ?? [];
    for (var questionItem in questionList) {
      print(questionItem["question"]);
    }
  } catch (err) {
    print(err);
  }
}
可选优化

如果需要更稳定的取值逻辑,可以增加两层判断避免API结构变动引发异常:

  • 先判断extractedData['response_code']是否为0,确认接口返回正常后再取数据
  • 对遍历的questionItem强转为Map<String, dynamic>类型,再读取字段属性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 01:06:08