0

When I Run the flutter program, this Exception has occurred.

RangeError (RangeError (index): Invalid value: Not in inclusive range 0..1: 2 how can I fix it**

Please explain what is range error and how can I solve them And why they occur and what is a possible solution to solve them.

import 'package:flutter/material.dart';
  
void main() => runApp(MyApp());
    
    class MyApp extends StatefulWidget {
      @override
      State<StatefulWidget> createState() {
        // TODO: implement createState
        return _MyAppState();
      }
    }
    
    class _MyAppState extends State<MyApp> {
      int _questionIndex = 0;
    
      void _answerQuestion() {
        setState(() {
          _questionIndex = _questionIndex + 1;
        });
        print(_questionIndex);
      }
    
      @override
      Widget build(BuildContext context) {
        var questions = [
          'What\'s your favorite color?',
          'What\'s your favorite animal?',
        ];
        return MaterialApp(
          home: Scaffold(
            appBar: AppBar(
              title: Text('My First App'),
            ),
            body: Column(
              children: [
                Text(
                  questions[_questionIndex],
                ),
                RaisedButton(
                  child: Text('Answer 1'),
                  onPressed: _answerQuestion,
                ),
                RaisedButton(
                  child: Text('Answer 2'),
                  onPressed: () => print('Answer 2 chosen!'),
                ),
                RaisedButton(
                  child: Text('Answer 3'),
                  onPressed: () {
                    // ...
                    print('Answer 3 chosen');
                  },
                ),
              ],
            ),
          ),
        );
      }
    }

2 Answers 2

1

First of all, put your questions outside the build method so that it can be accessed by _answerQuestion()

The main issue is _questionIndex is incremented continuously without caring about the max length of questions. @iamdipanshus already describe in details.

Changes will be

class _MyAppState extends State<MyApp> {
  int _questionIndex = 0;

  List<String> questions = [
    'What\'s your favorite color?',
    'What\'s your favorite animal?',
  ];

  void _answerQuestion() {
    if (_questionIndex < questions.length) {
      setState(() {
        _questionIndex = _questionIndex + 1;
      });
    }
    print(_questionIndex);
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
Sign up to request clarification or add additional context in comments.

Comments

1

Your questions is a list of n items, and you're trying to access the n+1th item

Basically, you can only access the items up to n only... no items exist beyond that... so, n+1, n+2, and so on are beyond the range... Stated as Not in inclusive range

in this case, you have only 2 questions, and on each _answerQuestion method call, you're incrementing the index, so on the 3rd press you'll get this error

To fix this, you can add a question length check in your _answerQuestion method

also, you can put your questions outside of build method


Try changing your code to following

class _MyAppState extends State<MyApp> {
      int _questionIndex = 0;

      /// convert it to var if you need it to be reassigned
      /// moved it to top get its length
      final questions = [
          'What\'s your favorite color?',
          'What\'s your favorite animal?',
        ];
    
      void _answerQuestion() {
        /// adding this line will ensure that the `_questionIndex`
        /// is incremented up to questions length
        if (_questionIndex < questions.length) {
          setState(() {
            _questionIndex = _questionIndex + 1;
          });
        }

        print(_questionIndex);
      }
    
      @override
      Widget build(BuildContext context) {

2 Comments

Can you include your code-snippet?
@YeasinSheikh well, it's more of an explanation... than code but sure, I'll add the suggested edits, thanx for suggestion

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.