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

Flutter测验应用弹出RangeError(index)错误求助

解决Flutter测验应用弹窗时的RangeError索引越界问题

错误原因

这个RangeError (index): Invalid value: Not in inclusive range 0..2 3错误,本质是当弹窗触发时,你的当前题目索引(比如_currentQuestionIndex)已经变为3,而题目列表只有3个元素(索引范围0-2),代码中仍在尝试用索引3访问题目列表,导致越界。

修复步骤

1. 清理弹窗内的越界访问

确保当索引等于题目总数(3)时,弹窗中不再访问questions[_currentQuestionIndex]——此时已经没有第4道题,弹窗只需要展示得分即可。

比如你可能写出了类似下面的错误代码:

// 错误示例:弹窗中错误访问了超出范围的索引
AlertDialog(
  title: Text(questions[_currentQuestionIndex].questionText), // 这里会触发索引越界
  content: Text("得分:$_score"),
  // ...
)

修复为只展示得分相关内容:

// 正确示例:弹窗仅展示结果,不访问越界索引
AlertDialog(
  title: const Text("测验完成"),
  content: Text("你的得分:$_score/${questions.length}"),
  // ...
)

2. 确保重置逻辑完全归位

弹窗关闭时的重置操作,必须将索引和得分都重置到初始状态:

TextButton(
  onPressed: () {
    setState(() {
      _currentQuestionIndex = 0; // 索引归零
      _score = 0; // 得分重置
    });
    Navigator.of(context).pop();
  },
  child: const Text("重新开始"),
)

3. 给索引访问加边界校验

在所有访问questions[_currentQuestionIndex]的地方,先判断索引是否在合法范围内,比如构建题目UI时:

@override
Widget build(BuildContext context) {
  // 索引超出范围时,直接触发结果逻辑,避免后续越界访问
  if (_currentQuestionIndex >= questions.length) {
    return Center(
      child: ElevatedButton(
        onPressed: () => _showResultDialog(context),
        child: const Text("查看结果"),
      ),
    );
  }
  // 正常展示题目UI
  return Scaffold(
    body: Column(
      children: [
        Text(questions[_currentQuestionIndex].questionText),
        // 选项按钮等内容
      ],
    ),
  );
}

总结

核心问题就是弹窗触发时索引已经超出题目列表范围,却仍在尝试访问该索引对应的元素。只要确保弹窗中不涉及越界的列表访问,同时重置逻辑正确归位索引,就能解决这个错误。

内容的提问来源于stack exchange,提问作者Xander van Zyl

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 22:25:24