Flutter错误:RangeError(索引):无效值:不在包含范围0..2内:3

huangapple go评论55阅读模式
英文:

Flutter Error : RangeError (index): Invalid value: Not in inclusive range 0..2: 3

问题

I'm new to flutter and I'm making a quiz app with 3 questions but I get this error after the 3rd question:

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

这是我的代码:

import 'package:flutter/material.dart';

import './question.dart';

import './answer.dart';

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

class MyApp extends StatefulWidget {
  MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  var questionIndex = 0;
  void AnsweredQuestion() {
    setState(() {
      questionIndex = questionIndex + 1;
    });
  }

  @override
  Widget build(BuildContext context) {
    var questions = [
      {
        'questiontext': 'What is Your Favourite Food?',
        'answers': ['Pizza', 'Humburger', 'Hotdog', 'Taco']
      },
      {
        'questiontext': 'What is Your Favourite Animal?',
        'answers': ['Tiger', 'Lion', 'Parrot', 'None']
      },
      {
        'questiontext': 'What is Your Favourite Color?',
        'answers': ['Black', 'Blue', 'Red', 'Green']
      }
    ];
    var a = questions[questionIndex]['answers'] as List;
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Center(
            child: Text('Quiz App'),
          ),
          backgroundColor: Colors.blue,
        ),
        body: questionIndex < questions.length
            ? Center(
                child: Column(
                  children: [
                    Question(
                        questions[questionIndex]['questiontext'] as String),
                    ElevatedButton(
                        onPressed: AnsweredQuestion, child: Answer(a[0])),
                    ElevatedButton(
                        onPressed: AnsweredQuestion, child: Answer(a[1])),
                    ElevatedButton(
                        onPressed: AnsweredQuestion, child: Answer(a[2])),
                    ElevatedButton(
                        onPressed: AnsweredQuestion, child: Answer(a[3])),
                  ],
                ),
              )
            : Center(child: Text('You Finished The Quiz!')),
      ),
    );
  }
}

我尝试更改questionIndex或更改其位置,并且我还检查了其他相关的问题以解决我的问题,但是我无法解决它,当将questions.length替换为2时,代码可以正常工作。

谢谢您的帮助。

英文:

I'm new to flutter and I'm making a quiz app with 3 questions but I get this error after the 3rd question:

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

This is my code:

import &#39;package:flutter/material.dart&#39;;
import &#39;./question.dart&#39;;
import &#39;./answer.dart&#39;;
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
MyApp({super.key});
@override
State&lt;MyApp&gt; createState() =&gt; _MyAppState();
}
class _MyAppState extends State&lt;MyApp&gt; {
var questionIndex = 0;
void AnsweredQuestion() {
setState(() {
questionIndex = questionIndex + 1;
});
}
@override
Widget build(BuildContext context) {
var questions = [
{
&#39;questiontext&#39;: &#39;What is Your Favourite Food?&#39;,
&#39;answers&#39;: [&#39;Pizza&#39;, &#39;Humburger&#39;, &#39;Hotdog&#39;, &#39;Taco&#39;]
},
{
&#39;questiontext&#39;: &#39;What is Your Favourite Animal?&#39;,
&#39;answers&#39;: [&#39;Tiger&#39;, &#39;Lion&#39;, &#39;Parrot&#39;, &#39;None&#39;]
},
{
&#39;questiontext&#39;: &#39;What is Your Favourite Color?&#39;,
&#39;answers&#39;: [&#39;Black&#39;, &#39;Blue&#39;, &#39;Red&#39;, &#39;Green&#39;]
}
];
var a = questions[questionIndex][&#39;answers&#39;] as List;
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Center(
child: Text(&#39;Quiz App&#39;),
),
backgroundColor: Colors.blue,
),
body: questionIndex &lt; questions.length
? Center(
child: Column(
children: [
Question(
questions[questionIndex][&#39;questiontext&#39;] as String),
ElevatedButton(
onPressed: AnsweredQuestion, child: Answer(a[0])),
ElevatedButton(
onPressed: AnsweredQuestion, child: Answer(a[1])),
ElevatedButton(
onPressed: AnsweredQuestion, child: Answer(a[2])),
ElevatedButton(
onPressed: AnsweredQuestion, child: Answer(a[3])),
],
),
)
: Center(child: Text(&#39;You Finished The Quiz!&#39;)),
),
);
}
}

I tried changing the questionIndex or changing its place and I also checked other related questions to solve my problem but I could not solve it, the code works fine when replacing questions.length by 2.

Thank You For Your Help.

答案1

得分: 1

根据错误消息,很明显您超出了范围。范围从0到2,而您试图访问第3个索引,所以问题出在以下代码行,位于var questions的下方:

var a = questions[questionIndex]['answers'] as List;

由于您没有添加检查长度的条件,它会引发错误,因此您可以用以下代码行替换上述代码:

var a = questionIndex < questions.length ? questions[questionIndex]['answers'] as List : [];

英文:

As per error message , it is clear that you are going out of the range . Range is from 0 to 2 and you are trying to access 3rd index so issue goes at this line which is just below of var questions

var a = questions[questionIndex][&#39;answers&#39;] as List;

As you haven't added condition to check about length , it is throwing error so you can replace above code with below line of code

var a = questionIndex &lt; questions.length ? questions[questionIndex][&#39;answers&#39;] as List : [];

huangapple
  • 本文由 发表于 2023年5月17日 18:27:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/76271115.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定