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

Flutter应用启动触发RangeError(index)错误求助

Flutter启动红屏RangeError问题排查与修复

错误信息

======== Exception caught by widgets library =======================================================
The following RangeError was thrown building MyHomePage(dirty, state: _MyHomePageState#d9dce):
RangeError (index): Invalid value: Valid value range is empty: 0

问题根源

  1. answers列表未初始化:qlist.dart里的initState()是游离方法,不属于任何State类,根本不会执行,导致answers为空,访问answers[0]触发越界。
  2. colorsList长度不足:只初始化了3个元素,但代码中访问了colorsList[3],同样触发索引越界。
  3. 题目切换无边界检查:nextQuestion方法没有判断是否到最后一题,会导致currentQuestion超出题目列表范围。

修复后的代码

main.dart

import 'package:flutter/material.dart';
import 'package:australia/qlist.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List<Color> colorsList = [Colors.white, Colors.white, Colors.white, Colors.white];
  List<String> answers = [];

  @override
  void initState() {
    super.initState();
    _loadAnswers();
  }

  void _loadAnswers() {
    final currentQ = QuestionsList.shared.getCurrentQuestion();
    answers.clear();
    answers.addAll([
      currentQ.correctAnswer,
      currentQ.dis1,
      currentQ.dis2,
      currentQ.dis3,
    ]);
    answers.shuffle();
    setState(() {
      colorsList = List.generate(4, (_) => Colors.white);
    });
  }

  @override
  Widget build(BuildContext context) {
    final currentQ = QuestionsList.shared.getCurrentQuestion();
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Column(children: [
        Center(child: Text(currentQ.question)),
        ...List.generate(4, (index) {
          return Card(
            color: colorsList[index],
            child: InkWell(
              onTap: () {
                setState(() {
                  colorsList[index] = answers[index] == currentQ.correctAnswer ? Colors.green : Colors.red;
                });
              },
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Text(answers[index]),
              ),
            ),
          );
        }),
        ElevatedButton(
          onPressed: () {
            if (QuestionsList.shared.hasNextQuestion()) {
              QuestionsList.shared.nextQuestion();
              _loadAnswers();
            }
          },
          child: const Text('NEXT'),
        )
      ]),
    );
  }
}

qlist.dart

import 'package:australia/question.dart';

class QuestionsList {
  List<Question> qList = [];
  int currentQuestion = 0;

  static QuestionsList shared = QuestionsList._init();

  QuestionsList._init() {
    qList.add(Question("Вопрос 1", "первый вар", "1 ываыва", "1 ываыва", "1ываываыа"));
    qList.add(Question("Вопрос 2", "второй", "2 ыа", " 2 ыаыва", "2 ываываыва"));
    qList.add(Question("Вопрос 3", "sdf", "345", "sfsfs", "dgdfg"));
    qList.add(Question("Вопрос 4", "sdf", "345", "sfsfs", "dgdfg"));
    qList.add(Question("Вопрос 5", "sdf", "345", "sfsfs", "dgdfg"));
  }

  void nextQuestion() {
    if (currentQuestion < qList.length - 1) {
      currentQuestion++;
    }
  }

  bool hasNextQuestion() {
    return currentQuestion < qList.length - 1;
  }

  Question getCurrentQuestion() {
    return qList[currentQuestion];
  }
}

question.dart

class Question {
  late final String question;
  late final String correctAnswer;
  late final String dis1;
  late final String dis2;
  late final String dis3;

  Question(this.question, this.correctAnswer, this.dis1, this.dis2, this.dis3);
}

修复说明

  • 将answers列表移到_MyHomePageState中,通过initState()初始化,确保页面加载时填充数据。
  • 扩展colorsList到4个元素,匹配选项数量,同时用List.generate简化初始化。
  • 给QuestionsList添加hasNextQuestion()方法,避免切换到不存在的题目。
  • 用List.generate循环生成选项卡片,减少重复代码。
  • 点击选项时,正确答案标绿,错误标红,提升交互反馈。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 05:25:25