Dart 错误,此构造函数应初始化字段 'x',因为其类型 'int' 不允许为 null
Dart error, This constructor should initialize field 'x' because its type 'int' doesn't allow null
我是 Dart 新手。这是我的代码:
class Point {
int x;
int y;
Point(this.x, this.y);
Point.same(int i) {
x = i;
y = i;
}
}
main() {}
我在 运行 时遇到了这个错误。
bin/dart1.dart:7:3: Error: This constructor should initialize field 'x' because its type 'int' doesn't allow null.
Point.same(int i) {
^
bin/dart1.dart:2:7: Context: 'x' is defined here.
int x;
^
bin/dart1.dart:7:3: Error: This constructor should initialize field 'y' because its type 'int' doesn't allow null.
Point.same(int i) {
^
bin/dart1.dart:3:7: Context: 'y' is defined here.
int y;
^
据我了解,Point.same()
的参数int i
是不可为空的,我用它来初始化x
和y
(x = i; y = i;
).为什么它仍然要求我初始化 x
和 y
?我什至尝试了以下代码,但仍然出现相同的错误:
class Point {
int x;
int y;
Point(this.x, this.y);
Point.same() {
x = 3;
y = 3;
}
}
main() {}
从不带构造函数参数的构造函数初始化字段时,使用 initializer list。它在构造函数主体之前运行,允许您初始化 final 和不可为 null 的变量,而无需将它们标记为延迟。
class Point {
int x;
int y;
Point(this.x, this.y);
Point.same(int i) :
x = i,
y = i;
}
main() {}
我是 Dart 新手。这是我的代码:
class Point {
int x;
int y;
Point(this.x, this.y);
Point.same(int i) {
x = i;
y = i;
}
}
main() {}
我在 运行 时遇到了这个错误。
bin/dart1.dart:7:3: Error: This constructor should initialize field 'x' because its type 'int' doesn't allow null.
Point.same(int i) {
^
bin/dart1.dart:2:7: Context: 'x' is defined here.
int x;
^
bin/dart1.dart:7:3: Error: This constructor should initialize field 'y' because its type 'int' doesn't allow null.
Point.same(int i) {
^
bin/dart1.dart:3:7: Context: 'y' is defined here.
int y;
^
据我了解,Point.same()
的参数int i
是不可为空的,我用它来初始化x
和y
(x = i; y = i;
).为什么它仍然要求我初始化 x
和 y
?我什至尝试了以下代码,但仍然出现相同的错误:
class Point {
int x;
int y;
Point(this.x, this.y);
Point.same() {
x = 3;
y = 3;
}
}
main() {}
从不带构造函数参数的构造函数初始化字段时,使用 initializer list。它在构造函数主体之前运行,允许您初始化 final 和不可为 null 的变量,而无需将它们标记为延迟。
class Point {
int x;
int y;
Point(this.x, this.y);
Point.same(int i) :
x = i,
y = i;
}
main() {}