Flutter Error : RangeError (index): Invalid value: Not in inclusive range 0..2: 3

Advertisements

I’m new to flutter and I’m making a quiz app with 3 questions but I get this error after the 3rd question:

RangeError (index): Invalid value: Not in inclusive range 0..2: 3

This is my code:

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']
      }
    ];
    var a = questions[questionIndex]['answers'] as List;
    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),
                    ElevatedButton(
                        onPressed: AnsweredQuestion, child: Answer(a[0])),
                    ElevatedButton(
                        onPressed: AnsweredQuestion, child: Answer(a[1])),
                    ElevatedButton(
                        onPressed: AnsweredQuestion, child: Answer(a[2])),
                    ElevatedButton(
                        onPressed: AnsweredQuestion, child: Answer(a[3])),
                  ],
                ),
              )
            : Center(child: Text('You Finished The Quiz!')),
      ),
    );
  }
}

I tried changing the questionIndex or changing its place and I also checked other related questions to solve my problem but I could not solve it, the code works fine when replacing questions.length by 2.

Thank You For Your Help.

>Solution :

As per error message , it is clear that you are going out of the range . Range is from 0 to 2 and you are trying to access 3rd index so issue goes at this line which is just below of var questions

var a = questions[questionIndex]['answers'] as List;

As you haven’t added condition to check about length , it is throwing error so you can replace above code with below line of code

var a = questionIndex < questions.length ? questions[questionIndex]['answers'] as List : [];

Leave a ReplyCancel reply