Home > Enterprise >  Flutter. RangeError (index)
Flutter. RangeError (index)

Time:02-02

I'm just learning and trying to make my first app. Please help me find the problem. When starting the application, it gives a red screen and an error:

======== 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

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> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter  ;
    });
  }

  List<Color> colorsList = [Colors.white, Colors.green, Colors.red];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: Column(children: [
          Center(
              child: Text(QuestionsList.shared.getCurrentQuestion().question)),
          Card(
            color: colorsList[0],
            child: InkWell(
              child: Text(answers[0]),
              onTap: () {
                if (answers[0] ==
                    QuestionsList.shared.getCurrentQuestion().correctAnswer) {
                  colorsList[0] = Colors.green;
                  setState(() {});
                }
              },
            ),
          ),
          Card(
            color: colorsList[1],
            child: InkWell(
              child: Text(answers[1]),
              onTap: () {
                if (answers[1] ==
                    QuestionsList.shared.getCurrentQuestion().correctAnswer) {
                  colorsList[1] = Colors.green;
                  setState(() {});
                }
              },
            ),
          ),
          Card(
            color: colorsList[2],
            child: InkWell(
              child: Text(answers[2]),
              onTap: () {
                if (answers[2] ==
                    QuestionsList.shared.getCurrentQuestion().correctAnswer) {
                  colorsList[2] = Colors.green;
                  setState(() {});
                }
              },
            ),
          ),
          Card(
            color: colorsList[3],
            child: InkWell(
              child: Text(answers[3]),
              onTap: () {
                if (answers[3] ==
                    QuestionsList.shared.getCurrentQuestion().correctAnswer) {
                  colorsList[3] = Colors.green;
                  setState(() {});
                }
              },
            ),
          ),
          ElevatedButton(
              onPressed: () {
                QuestionsList.shared.nextQuestion();
                setState(() {});
              },
              child: Text('NEXT'))
        ]));
  }
}

'package:australia/qlist.dart':


import 'package:australia/question.dart';

class QuestionsList{
  List<Question> qList = [];
  var 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("Вопрос 2", "sdf", "345", "sfsfs", "dgdfg"));
    qList.add(Question("Вопрос 3", "sdf", "345", "sfsfs", "dgdfg"));
    qList.add(Question("Вопрос 4", "sdf", "345", "sfsfs", "dgdfg"));




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





}


List<String> answers = [];


@override void initState() {

  answers.addAll([QuestionsList.shared
      .getCurrentQuestion().correctAnswer,
    QuestionsList.shared
        .getCurrentQuestion().dis1,
    QuestionsList.shared
        .getCurrentQuestion().dis2,
    QuestionsList.shared
        .getCurrentQuestion().dis3,]);
  answers.shuffle();

}

'package:australia/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);
}


enter image description here

CodePudding user response:

Your colorsList is empty by default and inside each card you try to set a color for the card like this for example

color: colorsList[0],

Since the list is empty it can't get a color element at position 0.

Give the colorsList a default color and it should work.

CodePudding user response:

If you want to keep the default color as white and want to change color after clicking.

Try the below thing:

List<Color> colorsList = List<Color>.generate(4, (_) => Colors.white);

CodePudding user response:

It's decided. It was in the wrong place

List<String> answers = [];

@override
void initState() {
  answers.addAll([
    QuestionsList.shared.getCurrentQuestion().correctAnswer,
    QuestionsList.shared.getCurrentQuestion().dis1,
    QuestionsList.shared.getCurrentQuestion().dis2,
    QuestionsList.shared.getCurrentQuestion().dis3,
  ]);
  answers.shuffle();
}
  • Related