0
class A {
  A(int value){
    print(value);
  }
}

class B extends A{
  int x;

  B.one(this.x) : super(x);

  B.two(int x) : this.x = x, super(this.x); 
}

We have here a class called "B" that inherits from class "A". Class B has two constructors - B.one() and B.two(). But only B.one() works properly, and B.two() just throws an error. The question is - why ? In my opinion B.one() works exactly as B.two() - B.one() is just written in a shorter form. The problem is: dart simply does not let me in B.two() pass the value this.x to a super class. But in B.one() it let's me ! I'm passing the exactly same variable in a argument to an A class, but only B.one() let's me do it. What on earth is the difference between working of those two constructors ?

I encountered this solution:

class A {
  A(int value){
    print(value);
  }
}

class B extends A{
  int x;

  B.one(this.x) : super(x);

  B.two(int x) : this.x = x, super(x); 
}

Simply removing this keyword from B.two() - it works. But now it referes not to a variable declared in a field of B class - it passess to a super class variable declared in this constructor. Why on earth do I have to take this approach in B.two() but in B.one() I can just pass the x field to a super class ? That solution simply does not answer my question.

Christopher Moore
  • 15,626
  • 10
  • 42
  • 52
  • *"B.two() just throws an error."* Mind to share what error? – derpirscher Aug 26 '23 at 15:09
  • Error: Can't access 'this' in a field initializer. - That is my other concern. I read in a documentation that dart omits using this keyword. From what I understand this keyword is omitted by dart in B.one(this.x) : super(x), because the super(x) is refering to a field of class B. But when I try to insert this keyword into this line, the compiler simply throws an error exact as in B.two() (Error: Can't access 'this' in a field initializer.). – newlunch Aug 26 '23 at 15:27
  • 1
    See https://stackoverflow.com/a/63319094/. `this` is simply not valid before invoking the base-class constructor. – jamesdlin Aug 26 '23 at 16:50

0 Answers0