为什么这个oops概念代码不工作?

  • 本文关键字:代码 工作 oops oop dart
  • 更新时间 :
  • 英文 :


我是新来的。我很惊讶为什么这个不工作!

class MicroPhone {

String name;
String color;
int model;
}
main() {
var mic = new MicroPhone();
mic.name = " Blue Yeti";
mic.color = "Silver";
mic.model = 1234;
print(mic);
}

显示:

test.dart:3:10: Error: Field 'name' should be initialized because its type 'String' doesn't allow null.
String name;
^^^^
test.dart:4:10: Error: Field 'color' should be initialized because its type 'String' doesn't allow null.
String color;
^^^^^
test.dart:5:7: Error: Field 'model' should be initialized because its type 'int' doesn't allow null.
int model;
^^^^^

你能解释为什么吗?

您显然正在使用非空默认(NNBD)版本的Dart。这三个成员变量需要初始化为非空值(通过您没有的构造函数),您必须通过在类型后面加上问号来告诉Dart它们为空是可以的。

在dart.dev中有关于如何在nnbd之前的世界中生活的文档,但是如果你为了将来习惯这种方式会更好。详见https://dart.dev/null-safety

相关内容

最新更新