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

Flutter开发测验应用添加答案时报The expression doesn't evaluate to a function错误求解

问题解决方案

你遇到的报错由3个代码错误共同导致,按优先级修改即可:

1. 修复addNewBool方法的实例调用错误

报错的直接触发点就是这里:你创建了Answer类的实例newBool后,错误地将其作为函数加括号调用,Answer实例本身不是可执行函数,所以抛出对应报错。
另外你要存入answers列表的是布尔值,直接取Answer实例的correctAnswer属性即可,修改代码如下:

void addNewBool(bool txAnswer) {
  final newBool = Answer(
    correctAnswer: txAnswer,
  );
  setState(() {
    // 删掉原来的newBool(),改为取属性
    answers.add(newBool.correctAnswer);
  });
}

2. 修复添加题目页的参数类型不匹配问题

你在AddQuestions页面中从输入框拿到的答案是字符串类型("true"/"false"),但addNewBool要求传入布尔类型,直接传字符串会触发类型不匹配报错,需要先做类型转换。
修改submitInput方法代码:

void submitInput() {
  final enteredTitle = titleController.text;
  // 输入为空直接终止逻辑,避免无效数据
  if (enteredTitle.isEmpty || answerController.text.isEmpty) return;
  final enteredBoolStr = answerController.text.toLowerCase();
  // 把字符串转成布尔值
  final enteredBool = enteredBoolStr == 'true';
  addQu(enteredTitle);
  addBoo(enteredBool);
  // 提交成功后自动返回测验页
  Navigator.pop(context);
}

3. 修复添加按钮的点击触发逻辑

你当前的添加按钮没有正确绑定点击事件,只写了submitInput没有加调用括号,点击按钮不会触发提交逻辑,修改代码:

FlatButton(
  // 原来的submitInput改为submitInput(),或者直接简写为onPressed: submitInput
  onPressed: () => submitInput(),
  child: Text('Add button'),
)

额外优化建议

你定义的_questions列表第一个元素多了一层大括号,是Set类型,和后面的字符串类型不一致,建议删掉多余大括号:

var _questions = [
  // 删掉原来的大括号
  'Victor loves computers',
  'Victor is learning Flutter',
  'Victor\'s favorite team is Manchester United',
  'Victor\'s favorite team is Chelsea'
];

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 21:15:02