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

i’m building a quiz app for pharmacists like me to prepare for professional exams. My app isn’t returning any error but i’m surprised at the error on my emulator.

Here’s my main.dart file:

import 'package:flutter/material.dart';
import 'package:quiz_app/question.dart';
import 'package:quiz_app/answer.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    var questions = ['What is your fav color?', 'What is your fav animal?'];

    var _questionIndex = 0;

    void _answerQuestion() {
      setState(() {
        _questionIndex = _questionIndex + 1;
      });
      print(_questionIndex);
    }

    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text("Quiz App"),
        ),
        body: Column(
          children: [
            Question(_questionIndex + 1, questions[_questionIndex]),
            Answer(_answerQuestion),
            Answer(_answerQuestion),
            Answer(_answerQuestion),
          ],
        ),
      ),
    );
  }
}

Here’s my answer.dart file:

import ‘package:flutter/material.dart’;

class Answer extends StatelessWidget {
  final Function selectHandler;

  Answer(this.selectHandler);

  //const Answer({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      width: double.infinity,
      // ignore: deprecated_member_use
      child: RaisedButton(
        color: Colors.blue,
        child: Text('Answer 1'),
        onPressed: selectHandler(),
      ),
    );
  }
}

And here’s my question.dart file:

import 'package:flutter/material.dart';

class Question extends StatelessWidget {
  final questionNumber;
  final questionText;

  // Question(String question, {Key? key, required this.questionText})
  //     : super(key: key);

  Question(this.questionNumber, this.questionText);

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.all(10),
      width: double.infinity,
      child: Text(
        '${questionNumber.toString()}. $questionText',
        style: TextStyle(fontSize: 24),
        textAlign: TextAlign.center,
      ),
    );
  }
}

Here’s the error on my emulator:

enter image description here

Source: Android Questions

LEAVE A COMMENT