更新时间:2022-12-13 22:38:48
您的问题是 this
尚不存在,因为仍在创建对象.Dart对象的构造分两个阶段完成,可能很难理解.
Your problem is that this
does not yet exists since the object are still being created. The construction of Dart objects is done in two phases which can be difficult to understand.
如果将程序更改为以下程序,它将起作用:
If you change you program to the following it will work:
abstract class OnClickHandler {
void doA();
void doB();
}
class MyClass {
OnClickHandler onClickHandler;
MyClass({this.onClickHandler});
void someFunction() {
onClickHandler.doA();
}
}
class Main implements OnClickHandler {
MyClass _myClass;
Main() {
_myClass = MyClass(onClickHandler: this);
}
@override
void doA() {}
@override
void doB() {}
}
原因是在构造函数中的 {}
内部运行的代码是在创建对象本身之后但在从构造函数返回对象之前执行的.
The reason is that code running inside { }
in the constructor are executed after the object itself has been created but before the object has been returned from the constructor.