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

Flutter代码报错:Quiz组件调用需3个位置参数但传入0个

解决Flutter中Quiz组件调用的参数错误问题

错误提示“3 positional argument(s) expected, but 0 found.”的核心原因是:你调用Quiz组件时使用了命名参数,但Quiz类的构造函数定义的是位置参数,Flutter无法将命名参数映射到要求的位置参数上,因此抛出错误。

两种解决方法:

方法1:修改Quiz组件为命名参数构造(推荐)

打开quiz.dart文件,将构造函数改为命名参数形式,提升代码可读性:

import 'package:flutter/material.dart';
import './question.dart';
import './answer.dart';

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

  // 命名参数需添加required(Flutter 2.0+)
  const Quiz({
    required this.answerQuestion,
    required this.questions,
    required this.questionIndex,
    Key? key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Question(questions[questionIndex]['questionText'] as String),
        ...(questions[questionIndex]['answer'] as List<String>)
            .map((answer) => Answer(() => answerQuestion(), answer))
            .toList(),
      ],
    );
  }
}

修改后,你原来的调用代码Quiz(answerQuestion: _answerQuestion, questions: _questions, questionIndex:_questionIndex)即可正常运行。

方法2:修改调用方式为位置参数

如果不想改动Quiz组件的构造函数,直接按构造函数定义的参数顺序传入值:

Quiz(_answerQuestion, _questions, _questionIndex)

⚠️注意:参数顺序必须和Quiz构造函数定义的顺序完全一致,否则会引发逻辑错误。

额外检查点

  • 确认quiz.dart中构造函数的参数类型与你传入的变量类型匹配:answerQuestion为Function类型,questions为List<Map<String, Object>>类型,questionIndex为int类型。
  • 若使用命名参数,Flutter 2.0及以上版本必须为必填参数添加required关键字,可选参数可添加?标记。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 09:39:25