问题
Lets say that I have an abstract class
abstract class OnClickHandler {
void doA();
void doB();
}
I have a class
class MyClass {
OnClickHandler onClickHandler;
MyClass({
this.onClickHandler
})
void someFunction() {
onClickHandler.doA();
}
}
And I have a class
class Main implements onClickHandler {
// This throws me an error
MyClass _myClass = MyClass(onClickHandler = this); // <- Invalid reference to 'this' expression
@override
void doA() {}
@override
void doB() {}
}
How can I say that use the same implementations that the Main class has? or is there an easier/better way to do this?
回答1:
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.
来源:https://stackoverflow.com/questions/62390624/dart-pass-this-as-a-parameter-in-a-constructor