当我学习Dart和Flutter时,我试图实现一个包含3个实例变量的简单类和一个使用构造函数语法糖的命名参数的构造函数,这里是该类的代码:
class Story {
String storyTitle;
String choice1;
String choice2;
Story({this.storyTitle, this.choice1, this.choice2});
}这在Android中运行得很好,应用程序使用实例变量也很好。当我在DartPad中尝试这样做时,我得到了以下错误:
Error compiling to JavaScript:
Warning: Interpreting this as package URI, 'package:dartpad_sample/main.dart'.
lib/main.dart:6:15:
Error: The parameter 'storyTitle' can't have a value of 'null' because of its type
'String', but the implicit default value is 'null'.
Story({this.storyTitle, this.choice1, this.choice2});
^^^^^^^^^^
lib/main.dart:6:32:
Error: The parameter 'choice1' can't have a value of 'null' because of its type
'String', but the implicit default value is 'null'.
Story({this.storyTitle, this.choice1, this.choice2});
^^^^^^^
lib/main.dart:6:46:
Error: The parameter 'choice2' can't have a value of 'null' because of its type
'String', but the implicit default value is 'null'.
Story({this.storyTitle, this.choice1, this.choice2});
^^^^^^^
Error: Compilation failed.根据我对文档的理解,这段代码应该像在Android上一样工作得很好,知道它为什么要在这里抛出错误吗?这段代码有效吗?
发布于 2021-06-11 16:25:04
你在安卓工作室上使用了一个旧版本的飞镖。在飞镖垫,你有最新的版本,有空安全启用。如果您想让dartpad代码工作,您可以在构造函数中为每个参数添加所需的内容,以便让dart知道您必须提供它。
就像这样:
class Story {
String storyTitle;
String choice1;
String choice2;
Story({required this.storyTitle, required this.choice1, required this.choice2});
}如果您想在android上拥有相同的版本,可以将pubspec.yml环境部分更改为从2.12.0开始,这将启用空安全
environment:
sdk: ">=2.12.0 <3.0.0"https://stackoverflow.com/questions/67940312
复制相似问题