首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么DartPad给出了与安卓工作室不同的结果?

为什么DartPad给出了与安卓工作室不同的结果?
EN

Stack Overflow用户
提问于 2021-06-11 16:12:31
回答 1查看 92关注 0票数 1

当我学习Dart和Flutter时,我试图实现一个包含3个实例变量的简单类和一个使用构造函数语法糖的命名参数的构造函数,这里是该类的代码:

代码语言:javascript
复制
class Story {
  String storyTitle;
  String choice1;
  String choice2;

  Story({this.storyTitle, this.choice1, this.choice2});
}

这在Android中运行得很好,应用程序使用实例变量也很好。当我在DartPad中尝试这样做时,我得到了以下错误:

代码语言:javascript
复制
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上一样工作得很好,知道它为什么要在这里抛出错误吗?这段代码有效吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-06-11 16:25:04

你在安卓工作室上使用了一个旧版本的飞镖。在飞镖垫,你有最新的版本,有空安全启用。如果您想让dartpad代码工作,您可以在构造函数中为每个参数添加所需的内容,以便让dart知道您必须提供它。

就像这样:

代码语言:javascript
复制
class Story {
  String storyTitle;
  String choice1;
  String choice2;

  Story({required this.storyTitle, required this.choice1, required this.choice2});
}

如果您想在android上拥有相同的版本,可以将pubspec.yml环境部分更改为从2.12.0开始,这将启用空安全

代码语言:javascript
复制
environment:
  sdk: ">=2.12.0 <3.0.0"
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67940312

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档