Andrey Solera
Andrey Solera

Reputation: 2402

Dart pass this as a parameter in a constructor

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?

Upvotes: 0

Views: 1288

Answers (1)

julemand101
julemand101

Reputation: 31219

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.

Upvotes: 2

Related Questions