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

Flutter类型转换报错:'() => Null'不是'(int) => void'的子类型

Flutter Quiz应用score传递类型转换错误修复方案

错误原因

  1. 类型强制转换违规:你将无参函数() { answerQuestion(...) }强制转换为void Function(int)类型,Dart不允许这种跨类型的强制转换,直接触发类型不匹配错误。
  2. 回调设计与按钮API不兼容:ElevatedButton的onPressed要求是无参的VoidCallback,但你定义的selectHandler是接收int参数的函数,同时onPressed的写法错误,没有正确执行回调逻辑。

修复步骤

1. 调整Answer组件的回调类型

将Answer类的回调改为VoidCallback(无参),并修正onPressed的赋值方式:

class Answer extends StatelessWidget {
  final String answerText;
  final VoidCallback selectHandler; // 改为无参回调类型

  const Answer(this.answerText, this.selectHandler, {super.key});

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      style: const ButtonStyle(
        backgroundColor: MaterialStatePropertyAll(Colors.cyan),
        foregroundColor: MaterialStatePropertyAll(Colors.blueAccent),
      ),
      onPressed: selectHandler, // 直接传递回调,无需额外包裹
      child: Text(answerText),
    );
  }
}

2. 修正Quiz组件的回调传递逻辑

移除错误的类型强制转换,直接创建绑定好score的无参回调:

class Quiz extends StatelessWidget {
  final List<Map<String, Object>> questions;
  final int questionIndex;
  final void Function(int) answerQuestion;

  const Quiz({
    required this.questions,
    required this.questionIndex,
    required this.answerQuestion,
    super.key,
  });

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        children: [
          Question(questions[questionIndex]['questionText'] as String),
          ...(questions[questionIndex]['answers'] as List<Map<String, Object>>)
              .map((answer) {
            return Answer(
              answer['text'] as String,
              // 创建无参回调,内部自动传入对应score
              () => answerQuestion(answer['score'] as int),
            );
          }).toList(),
        ],
      ),
    );
  }
}

修复效果

修改完成后,点击选项按钮会自动触发绑定好的回调,将对应选项的score传入answerQuestion函数,累计总分并切换题目,不会再出现类型转换错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 09:53:18