I get an error when I run that range error index: not inclusive range 0..3 4

Viewed 32

Below is my main.dart:

import 'package:flutter/material.dart';
import './questions.dart';
import './answers.dart';

/*void main(){   runApp(MyApp()); }*/
void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return MyAppState();
  }
}

class MyAppState extends State<MyApp> {
  var questionIndex = 0;
  void ansQuestion() {
    setState(() {
      questionIndex = questionIndex + 1;
    });
    print(questionIndex);
  }

  @override
  Widget build(BuildContext context) {
    var questions = [
      {
        'question': 'whats youre favourite color',
        'answers': ['red', 'blue', 'green', 'orange']
      },
      {
        'question': 'how did you sleep',
        'answers': ['well', 'good', 'badly', 'very badly']
      },
      {
        'question': 'how high can you jump',
        'answers': ['high', 'low', 'very high', 'so low']
      },
      {
        'question': 'are you silly',
        'answers': ['kinda', 'no', 'yes', 'i dont know']
      },
    ];
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: const Text('Simple Quiz App')),
        body: Column(
          children: [
            Question(
              questions[questionIndex]['question'] as String,
            ),
            ...(questions[questionIndex]['answers'] as List<String>)
                .map((answer) {
              return Answers(ansQuestion, answer);
            }).toList()
          ],
        ),
      ),
    );
  }
}

questions.dart:

import 'package:flutter/material.dart';

class Question extends StatelessWidget {
  @override
  final String myQuestions;
  Question(this.myQuestions);
  Widget build(BuildContext context) {
    return Container(
      width: double.infinity,
      margin: EdgeInsets.all(10),
      child: Text(myQuestions,
          style: TextStyle(fontSize: 20), textAlign: TextAlign.center),
    );
  }
}

and answers.dart:

import 'package:flutter/material.dart';

class Answers extends StatelessWidget {
  final Function selectHandler;
  final String answerText;
  Answers(this.selectHandler, this.answerText);
  @override
  Widget build(BuildContext context) {
    return Container(
      width: double.infinity,
      child: ElevatedButton(
        child: Text(answerText),
        onPressed: selectHandler(),
      ),
    );
  }
}
1 Answers

U need Control the Max Index that u can use.

Like this :

final int maxIdx = questions.length - 1;
questionIndex++;

If (questionIndex < maxIdx){
//Do something
} else {
 // Do something
}
Related