flutter dart 语言相关

igsr9ssn  于 2023-02-05  发布在  Flutter
关注(0)|答案(2)|浏览(109)

我尝试为问题创建一个类,以便在测验应用程序的main.dart文件中使用它,但遇到了一些错误。请告诉我为什么会出现这些错误以及如何解决这些错误?
课堂提问:

class Question {
  String questionText;
  bool questionAnswer;

  Question({String q, bool a}) {
    questionText = q;
    questionAnswer = a;
  }
}

错误:

Non-nullable instance field 'questionAnswer' must be initialized.
Non-nullable instance field 'questionText' must be initialized.
The parameter 'q' can't have a value of 'null' because of its type, but the implicit default value is 'null'.
The parameter 'a' can't have a value of 'null' because of its type, but the implicit default value is 'null'.

Image of Errors here.

bhmjp9jg

bhmjp9jg1#

这个问题是关于空值安全的,你需要在构造函数上使字段为空,late或add。

class Question {
  late String questionText;
  late bool questionAnswer;

  Question({required String q, required bool a}) {
    questionText = q;
    questionAnswer = a;
  }
}
class Question {
   String questionText;
   bool questionAnswer;

  Question({required this.questionAnswer, required this.questionText});
}

了解更多关于-null-safety的信息

42fyovps

42fyovps2#

Yeasin的答案可能是您想要的,但我想详细介绍一下零安全。
所以底层语言dart现在有了“null safety”,这意味着除非你告诉dart变量可以为null,否则当一个不可为null的变量没有得到一个变量时,它就会抱怨。
示例

class Question{
    String complaint; // complain because it is not initialised
    String fine = ""; // no complaint, because we have a string variable, though it is empty.
    late String lateString; // tells the compiler don't worry. I'll define it later in the constructor while the object in being created
    String nullable?; // tells the compiler this variable can be null

}

使用可以为null的变量会带来很多其他的事情需要考虑。所以我建议你仔细研究一下。我已经链接了一个关于这个主题的非常简单的视频(取决于你的技能,你可能可以找到一个更快的视频)
https://www.youtube.com/watch?v=llM3tcpaD5k

相关问题