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

Flutter开发测验应用获取题目列表时出现undefined_named_parameter错误

错误原因

你遇到的undefined_named_parameter错误由以下几个问题共同导致:

  • 你的Question类构造函数定义的是位置参数,但你在实例化时使用了命名参数的传参形式,Dart找不到对应的命名参数就会抛出该错误。
  • 模拟数据中存储正确答案下标的字段是answer_index,你调用时写的answer_id属于不存在的字段。
  • 模拟数据中存储选项的字段是options,你调用时写的option少了末尾的s,会获取到空值。
  • _question变量你调用了toList()转成了列表,但声明的类型是Iterable,类型不匹配。

修复方案

1. 适配命名参数传参写法

如果要保留你当前命名参数的传参形式,先修改Question类的构造函数,给参数加required命名修饰:

class Question {
  final int id, answer;
  final String question;
  final List<String> options;
  // 修改为命名参数构造
  Question({
    required this.id,
    required this.answer,
    required this.question,
    required this.options,
  });
}

2. 修正字段调用错误,调整变量类型

修改QuestionController中_question的初始化代码:

// 把类型调整为匹配的List<Question>
late List<Question> _questions = sampleData
  .map((question) => Question(
      id: question['id'],
      // 修正为读取answer_index字段
      answer: question['answer_index'],
      question: question['question'],
      // 修正为读取options字段,同时做类型转换避免警告
      options: List<String>.from(question['options']))
  ).toList();
// 可新增getter供外部访问题目列表
List<Question> get questions => _questions;

可选方案:保留原位置参数构造

如果你不想修改Question类的构造函数,直接按参数顺序传值即可,不需要写参数名:

late List<Question> _questions = sampleData
  .map((question) => Question(
      question['id'],
      question['answer_index'],
      question['question'],
      List<String>.from(question['options']))
  ).toList();

修改完成后重新运行即可解决报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 14:39:04