class Foo {
int count; // Error
void bar() => count = 0;
}
Run Code Online (Sandbox Code Playgroud)
为什么我已经在bar方法中初始化它时看到错误?如果count被标记为 ,我可以理解这个错误final。
class A {
A(int value);
}
class B extends A{
final int foo;
B.one(this.foo) : super(foo); // Works
B.two(int foo) : foo = foo, super(this.foo); // Doesn't work
}
Run Code Online (Sandbox Code Playgroud)
在 中B.one,我可以轻松地将 的值传递给footosuper但在 中B.two,我不能这样做。在这两种情况下,该字段foo都是在调用之前分配的super,在一种情况下它有效,在另一种情况下它失败。所以,问题是在构造函数中什么时候创建字段。
在 Dart 中,立即赋值与在 Java 中的构造函数中是否有区别?
class Example {
int x = 3;
}
Run Code Online (Sandbox Code Playgroud)
对比
class Example {
int x;
Example() {
x = 3;
}
}
Run Code Online (Sandbox Code Playgroud)
我问是因为当我使用 Flutter 并尝试将一个使用 setState 的函数分配给一个变量时,前一种方法是不可能的,但后一种方法是可能的。