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

Flutter答题应用完成答题后跳转结果页出现RangeError问题求助

Flutter答题应用答完最后一题跳转报错的解决方案

错误原因

你遇到的RangeError (length): Invalid value: Not in inclusive range 0..5: 6,是因为当前题目索引超出了questions数组的有效索引范围。假设你的questions数组有6个元素,有效索引是0到5,答完最后一题后代码错误地将索引更新为6,此时访问questions[6]就会触发越界错误。

修复步骤

  1. 调整跳转逻辑顺序
    不要先更新索引再判断是否到达最后一题,应该先判断当前是否是最后一题,再决定跳转结果页还是更新索引:

    setState(() {
      if (currentIndex == questions.length - 1) {
        // 跳转至结果页
        Navigator.push(context, MaterialPageRoute(builder: (context) => ResultPage()));
      } else {
        currentIndex++;
      }
    });
    
  2. 检查UI构建中的数组访问
    确保在构建题目UI时,只有当currentIndex处于0 <= currentIndex < questions.length范围内时,才访问questions[currentIndex],避免索引越界。

  3. 修正延迟跳转写法
    如果用延迟执行跳转,要确保延迟代码不会错误更新索引:

    setState(() {
      if (currentIndex == questions.length - 1) {
        Future.delayed(const Duration(seconds: 1), () {
          Navigator.push(context, MaterialPageRoute(builder: (context) => ResultPage()));
        });
      } else {
        currentIndex++;
      }
    });
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 17:09:54