Dart pass this as a parameter in a constructor

不羁的心 提交于 2021-02-17 05:58:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!