首页 > 解决方案 > 为什么这个 oops 概念代码不起作用?

问题描述

我是飞镖的新手。我很惊讶为什么这个 OOP 不起作用!

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;
      ^^^^^

你能解释一下为什么吗?

标签: oopdart

解决方案


您显然正在使用 Dart 的默认非 Null (NNBD) 版本。这三个成员变量需要被初始化为非空值(通过一个你没有的构造函数),或者你必须告诉 Dart 通过跟随带问号的类型将它们为空值是可以的。

在 dart.dev 上有关于如何在 NNBD 之前的世界中生活的文档,但如果你以后习惯这种方式会更好。有关详细信息,请参阅https://dart.dev/null-safety


推荐阅读