Home > Net >  Exception has occurred. RangeError (RangeError (index): Invalid value: Not in inclusive range
Exception has occurred. RangeError (RangeError (index): Invalid value: Not in inclusive range

Time:02-19

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');
                  },
                ),
              ],
            ),
          ),
        );
      }
    }

CodePudding user response:

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(

CodePudding user response:

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) {
  • Related