0

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?

creativecreatorormaybenot
  • 114,516
  • 58
  • 291
  • 402
SdahlSean
  • 573
  • 3
  • 13
  • *"putting the this keyword into the parentheses in dart causes an error"* What error? Please show the full error message. – kaya3 Jan 21 '20 at 19:26

1 Answers1

3

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.
}
creativecreatorormaybenot
  • 114,516
  • 58
  • 291
  • 402