class Foo {
int count; // Error
void bar() => count = 0;
}
为什么我已经在bar
方法中初始化错误了?如果count
被标记为final
,我可以理解这个错误.
class Foo {
int count; // Error
void bar() => count = 0;
}
为什么我已经在bar
方法中初始化错误了?如果count
被标记为final
,我可以理解这个错误.
(Your code was fine before Dart 2.12, null safe)
使用空安全性,Dart无法知道您是否实际将变量分配给了count
.Dart可以通过三种方式查看初始化:
At the time of declaration:个
int count = 0;
In the initializing formals:个
Foo(this.count);
In the initializer list:个
Foo() : count = 0;
因此,根据Dart的说法,代码中从未初始化过count
,因此出现了错误.解决方案是用上面显示的3种方式初始化变量,或者只使用late
关键字,这将告诉Dart在使用变量之前,您将在其他点初始化变量.
Use the 100 keyword:
class Foo {
late int count; // No error
void bar() => count = 0;
}
Make variable nullable: