SdahlSean
SdahlSean

Reputation: 583

How do I use `this` in constructors?

In python if I call a method on an object a reference to the object itself is put into the function. I want to have a similar behaviour in dart but I can't find out how to get the same behaviour as in python with the self variable. I basicaly want to implement a behaviour like this:

class Parent:
    def __init__(self):
        self.child = Child(self)

class Child:
    def __init__(self, parent):
        self.parent = parent

In dart I would expect it to look somehow like this:

class Parent {
  final Child child;

  Parent() : this.child = Child(this);
}

class Child {
  final Parent parent;

  Child(parent) : this.parent = parent;
}

but putting the this keyword into the parentheses in dart causes an error. The error message is:

Error compiling to JavaScript:
main.dart:4:33:
Error: Can't access 'this' in a field initializer.
  Parent() : this.child = Child(this);
                                ^^^^
Error: Compilation failed.

How can I implement the behaviour demonstrated in the python code in dart?

Upvotes: 0

Views: 345

Answers (1)

creativecreatorormaybenot
creativecreatorormaybenot

Reputation: 126684

You cannot access this in neither the constructor head nor in the initializer list (learn more about what that is here).

If you want to do it, you will have to initialize your child variable in the constructor body:

class Parent {
  Parent() {
    child = Child(this);
  }

  Child child; // Cannot be final.
}

Upvotes: 3

Related Questions