范围错误索引无效值不在范围内,在Dart Flutter应用中为0..1(含2)

时间:2019-12-19 14:10:27

标签: android flutter dart mobile-application flutter-dependencies

我正在关注一个flutter应用程序教程,但遇到此错误:

  

范围错误索引无效值不在范围内,0..1(含2)

关于如何解决此问题的任何建议?

import 'package:flutter/material.dart';

//void main() {
  //runApp(MyApp());
//}
void main()=>runApp(MyApp()); 
class MyApp extends StatefulWidget{

  @override
 State<StatefulWidget> createState(){
   return MyAppState();

 }
}

class MyAppState extends State<MyApp>{

var questionIndex=0;

  void answerQuestion(){
    setState(() {
      questionIndex=questionIndex+1;
    });
   print(questionIndex);
    //print("answer choosen!");
  }
@override
  Widget build(BuildContext context){ 

var questions=['What is your favourite colour','what is favourite animal',];

return MaterialApp(home: Scaffold(
appBar:AppBar(title:Text('my first app'),),
body: Column(children:[Text(questions[questionIndex]),
        //RaisedButton(child: Text("Ansewr 1"), onPressed:()=>print("Answer 1"),),
        //RaisedButton(child: Text("Ansewr 1"),onPressed:answerQuestion),
        RaisedButton(child: Text("Ansewr 0"), onPressed:answerQuestion,),
        RaisedButton(child: Text("Ansewr 1"), onPressed:answerQuestion,),



          ],),

),);
  }
}

2 个答案:

答案 0 :(得分:0)

您的问题应包含错误在何时发生。但是我想您总共总共第二次点击了questionIndex个后,该错误出现了吗?

每次单击一个按钮时,您会增加Text(questions[questionIndex])并重新构建窗口小部件。在窗口小部件树的一部分中,编写questions。您的数组questionIndex=0包含两个问题。如果您启动应用Text(questions[questionIndex]),则第一个问题将显示在questionIndex=1处。如果单击按钮questionIndex,将显示第二个问题。如果再次单击其中一个按钮,则会将questions[questionIndex]增大到2。因此,现在您的小部件树尝试将问题移到# Creating engine engine = sqlalchemy.create_engine('mssql://*server_name*/*database_name*?trusted_connection=yes') 中的第三个位置。但是没有第三个问题,因此您的应用程序会崩溃。

答案 1 :(得分:0)

我修改了您的代码。也许对您有用。并且不要过多使用setState()方法。尝试学习bLoc架构。

void main() => runApp(MyApp());

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

enum Questions { firstQuestion, secondQuestion }

class MyAppState extends State<MyApp> {
var question = Questions.firstQuestion;

@override
Widget build(BuildContext context) {
var questions = [
  'What is your favourite colour',
  'what is favourite animal',
];

return MaterialApp(
  home: Scaffold(
    appBar: AppBar(
      title: Text('my first app'),
    ),
    body: Column(
      children: [
        Text(questions[question.index]),
        RaisedButton(
          child: Text("Ansewr 0"),
          onPressed: () {
            setState(() {
              question = Questions.firstQuestion;
            });
          },
        ),
        RaisedButton(
          child: Text("Ansewr 1"),
          onPressed: () {
            setState(() {
              question = Questions.secondQuestion;
            });
          },
        ),
      ],
    ),
  ),
);
}
}