Getting this Error RangeError (Index) Invalid Value: not in Exclusive Range 0..2 : 5 previou

Viewed 35

previously I was getting the of setState() or markneedsBuild() Called during the build for solving this error I call a function initState() now I am getting the range error. whos is going to solve this I'm in learning paise I don't know enough about flutter I'm a beginner I have provided my all file's code below

 **main.dart**       
            
        
  

 // ignore_for_file: prefer_const_constructors
      
        import 'package:flutter/material.dart';
        import 'package:flutter/scheduler.dart';
        import './questions.dart';
        import './answer.dart';
        
        void main() {
          runApp(Myapp());
        }
        
        class Myapp extends StatefulWidget {
          @override
          State<StatefulWidget> createState() {
            return MyappState();
          }
        }
        class MyappState extends State<Myapp> {
          var questionIndex = 0;
          @override
          void initState() {
            SchedulerBinding.instance!.addPostFrameCallback((_) {
              // fetch data
             answerChosen();
            });
          }
          answerChosen() {
            setState(() {
              questionIndex = questionIndex + 1;
            });
            
            // ignore: avoid_print
             print(questionIndex);
          }
           @override
          Widget build(BuildContext context) {
            var questions = [
              {
                'QuestionText': 'what is your favorite color',
                'Answers': ['red', 'greed', 'blue', 'Black']
              },
              {
                'QuestionText': 'what\'s your favorite animal',
                'Answers': ['cat', 'dog', 'lion', 'girgit']
              },
              {
                'QuestionText': 'Who\'s your favorite Player',
                'Answers': ['Messi', 'Neymar', 'Ronaldo', 'Other']
              }
            ];
            return MaterialApp(
              home: Scaffold(
                appBar: AppBar(
                  title: Text('My First App'),
                ),
                body: Column(
                  children: [
                    Question(
                      questions[questionIndex]['QuestionText'] as String,
                    ),
                    ...(questions[questionIndex]['Answers'] as List<String>).map(
                      (answer) {
                        return jawab(answerChosen, answer);
                      },
                    ).toList()
                  ],
                ),
              ),
            );
          }
        }
    

answer.dart

 import 'package:flutter/material.dart';
        class Answer extends StatelessWidget {
          final Function selectHandler;
          final String answerText;
           Answer(this.selectHandler, this.answerText);
          @override
          Widget build(BuildContext context) {
            return Container(
              width: double.infinity,
              child: RaisedButton(
                color: Colors.blue,
                textColor: Colors.white,
                child: Text(answerText),
                onPressed: selectHandler(),
              ),
            );
          }
        }
    
   

questions.dart

import 'package:flutter/material.dart';
        class Question extends StatelessWidget {
          final String questionText;
        
          Question(this.questionText);
        
          @override
          Widget build(BuildContext context) {
            return Container(
              width: double.infinity,
              margin: EdgeInsets.all(10),
              child: Text(
                questionText,
                style: TextStyle(fontSize: 28),
                textAlign: TextAlign.center,
              ),
            );
          }
        }
1 Answers

You are trying to match an index that is out of the questions range.

It can have a maximum index of 2. But when you chose an answer and you are on the last question, the questionIndex will become 3.

answerChosen() {
  // if it's on last index
  if(questions.length - 1 == questionIndex) {
    // do something else
    return;
  }

  setState(() {
    questionIndex = questionIndex + 1;
  });
}

Put the questions out of the build method, so you can get the last index dynamic in the condition from the first line from answerChosen.

I hope that my answer helped you! :)

Related