【问题标题】:Why am I receiving a RangeError at compile time in this app?为什么我在此应用程序的编译时收到 RangeError?
【发布时间】:2021-07-03 15:16:52
【问题描述】:

您好,提前感谢您提供任何可能的帮助。

使用以下代码,我收到 RangeError。有谁知道为什么会这样? 在编译时应该捕获的范围之外,我没有看到任何参考。我知道用户可能会多次按下按钮并会产生错误(我只是在教程中进行操作,我们稍后会解决),但这在教程的编译时没有发现.

新版本的 Flutter 或 Dart 中是否有一些额外的编译时验证可能会导致这种情况?

再次感谢您的帮助。

======== 小部件库捕获的异常 =============================== ======================= 在构建 MyApp(dirty) 时引发了以下 RangeError: RangeError(索引):无效值:不在包含范围 0..2:4

import 'package:flutter/material.dart';

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);
  }

  @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'),
            onPressed: answerQuestion,
          ),
        ]),
      ),
    );
  }
}

【问题讨论】:

  • 因为你的问题的长度是有限制的......而且你不断增加一个整数值而没有考虑到这一点
  • 这条线看起来很可疑。 questionIndex = questionIndex + 1; 如果你根据questions 的长度检查这个会发生什么?
  • 这不是运行时错误吗?
  • 最好只处理RangeError 并按照教程进行操作

标签: flutter dart


【解决方案1】:

因为您想在按下按钮时增加问题编号。您应该在按下按钮时调用该函数。 所以改变

RaisedButton(
        child: Text('Answer'),
        onPressed:() { answerQuestion() },
      )                        

【讨论】:

  • onPressed:将函数作为输入。如果在 answerQuestion 的末尾添加括号,则不再传递函数,而是传递函数的返回值。
  • 哦!是的,它应该是这样的 - onPressed:() { answerQuestion() }
  • () 被称为括号!!
猜你喜欢
  • 1970-01-01
  • 2012-03-13
  • 1970-01-01
  • 1970-01-01
  • 2018-01-13
  • 2015-11-30
  • 2023-02-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多