oop - 为什么这个 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;
^^^^^
你能解释一下为什么吗?
解决方案
您显然正在使用 Dart 的默认非 Null (NNBD) 版本。这三个成员变量需要被初始化为非空值(通过一个你没有的构造函数),或者你必须告诉 Dart 通过跟随带问号的类型将它们为空值是可以的。
在 dart.dev 上有关于如何在 NNBD 之前的世界中生活的文档,但如果你以后习惯这种方式会更好。有关详细信息,请参阅https://dart.dev/null-safety。
推荐阅读
- django - 检查 Django 模板上下文变量中是否存在文本
- excel - 为什么在使用 For Each Next 循环之前不需要设置对象变量?
- c - 使用 scanf() 处理过度输入
- apache-spark - 如何有效地对 spark 数据集中的每 k 行进行分组?
- composer-php - 如何将具有相同前缀的多个存储库添加到作曲家?
- javascript - 在不工作的情况下设置日期输入值
- python - ImportError:将views.py拆分为多个文件后没有名为模型的模块
- python - 如何修复错误的位置程序
- vue.js - 来自 vue 当前组件的访问方法
- python - 如何使用 redis for python 在 Redis 中搜索值