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

Flutter测验应用如何实现选答案后无需点击按钮自动跳转页面?

测验应用自动跳转功能修改方案

你现有代码的核心逻辑已经包含了选答案后延迟跳转的实现,只需要修复2处明显错误,再补充1道防重复点击的逻辑即可:

1. 修正参数类型不匹配问题

你在QuestionCard中给checkAns传的是int类型的选项下标,但checkAns方法定义的形参是String类型,首先要修改参数类型:

// 把参数selectedIndex的类型从String改为int,和传入的下标类型匹配
void checkAns(Question question, int selectedIndex) {
    // 新增:已答题的情况下直接返回,防止用户重复点击多次计分
    if(_isAnswered) return;
    _isAnswered = true;
    // 修复原逻辑错误:正确答案取当前题目对应的正确选项下标,不要赋值整个options数组
    // 请把correctAnswerIndex替换为你Question类中存储正确答案下标的字段名
    _correctAns = question.correctAnswerIndex;
    _selectedAns = selectedIndex;

    if (_correctAns == _selectedAns) _numOfCorrectAns++;
    update();

    // 原有延迟跳转逻辑保留,1秒后自动切页
    Future.delayed(Duration(seconds: 1), () {
      if (_questionNumber.value != _questions.length) {
        _isAnswered = false;
        _pageController.nextPage(
            duration: Duration(milliseconds: 100), curve: Curves.ease);
      } else {
        Get.off(ScoreScreen());
      }
    });
}

2. 确认Option组件的点击绑定正确

你没贴全Option组件的build代码,需要确保组件的点击事件正确绑定了传入的press回调,示例如下:

class Option extends StatelessWidget {
  const Option({
    Key? key,
    required this.text,
    required this.index,
    required this.press,
  }) : super(key: key);

  final String text;
  final int index;
  final VoidCallback press;

  @override
  Widget build(BuildContext context) {
    // 确保点击选项时触发press回调
    return GestureDetector(
      onTap: press,
      child: Container(
        margin: EdgeInsets.only(top: 15),
        padding: EdgeInsets.all(15),
        decoration: BoxDecoration(
          border: Border.all(color: Colors.grey),
          borderRadius: BorderRadius.circular(10),
        ),
        child: Row(
          children: [
            Text("${index + 1}. $text"),
          ],
        ),
      ),
    );
  }
}

3. 原有press绑定无需修改

QuestionCard里的press: () => _controller.checkAns(question, index)逻辑完全符合需求,不需要改动。
修改完成后,用户点击选项就会自动完成判分、1秒后跳转到下一题,全部答完自动进入得分页,不需要额外的跳转按钮。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 22:57:03