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

Flutter Quiz应用答完第3题后出现RangeError(index)错误求助

问题根源

你遇到的RangeError是因为在判断索引是否合法之前,就直接访问了questions[questionIndex]。当答完第3题后,questionIndex变为3,而questions数组的长度是3,合法索引范围是0-2。此时var a = questions[questionIndex]['answers'] as List;这行代码会直接尝试访问questions[3],导致索引越界错误。

你的条件判断questionIndex < questions.length只控制了body的显示内容,但这行获取答案列表的代码在判断之前就执行了,所以即使已经完成答题,这行代码还是会被触发,引发错误。

修复方案

把获取答案列表的逻辑移到条件判断的内部,确保只有当索引合法时才去访问questions数组,同时可以用map方法简化按钮生成逻辑:

修改后的完整代码:

import 'package:flutter/material.dart';

import './question.dart';
import './answer.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  var questionIndex = 0;
  
  void AnsweredQuestion() {
    setState(() {
      questionIndex = questionIndex + 1;
    });
  }

  @override
  Widget build(BuildContext context) {
    var questions = [
      {
        'questiontext': 'What is Your Favourite Food?',
        'answers': ['Pizza', 'Humburger', 'Hotdog', 'Taco']
      },
      {
        'questiontext': 'What is Your Favourite Animal?',
        'answers': ['Tiger', 'Lion', 'Parrot', 'None']
      },
      {
        'questiontext': 'What is Your Favourite Color?',
        'answers': ['Black', 'Blue', 'Red', 'Green']
      }
    ];

    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Center(
            child: Text('Quiz App'),
          ),
          backgroundColor: Colors.blue,
        ),
        body: questionIndex < questions.length
            ? Center(
                child: Column(
                  children: [
                    Question(
                        questions[questionIndex]['questiontext'] as String),
                    // 仅在索引合法时生成答案按钮,用map简化重复代码
                    ...(questions[questionIndex]['answers'] as List).map((answer) {
                      return ElevatedButton(
                        onPressed: AnsweredQuestion, 
                        child: Answer(answer)
                      );
                    }).toList(),
                  ],
                ),
              )
            : Center(child: Text('You Finished The Quiz!')),
      ),
    );
  }
}

额外优化建议

  • 用map遍历答案生成按钮,避免手动写重复的ElevatedButton,后续如果答案数量变化,代码可以自动适配。
  • 可以给AnsweredQuestion加个边界判断,防止索引意外超出范围:
void AnsweredQuestion() {
  setState(() {
    if (questionIndex < questions.length - 1) {
      questionIndex += 1;
    }
  });
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 16:05:37