Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I call super inside constructor body?

Tags:

flutter

dart

class Foo {
  Foo(int y); 
}

class Bar extends Foo { 
  int value;

  Bar(int x) { // error in this line
    value = x;
    print("Hi there");
    super(x); // error in this line
  }
}

How can I call super inside constructor body?


Note:

I know I can use initialiser list to solve it but I would like to know how to call super inside method body?

Bar(int x): value = x, super(x); // works but I am not looking for it. 
like image 368
iDecode Avatar asked Oct 29 '25 05:10

iDecode


1 Answers

Dart does not support inheriting the constructors as explicitly callable methods. The initializer list you mentioned is the supported way to call unnamed super constructors in Dart.

However, you can achieve what you want with the help of named constructors. Take a look at the below example -

class Foo {
  int superValue;

  Foo(); //A default zero-argument constructor

  Foo._init(this.superValue); //Named constructor

  void initValue(int x) => Foo._init(x);
}

class Bar extends Foo { 
  int value;

  Bar(int x) {
    value = x;
    print("Hi there");
    super.initValue(x);
  }
}

void main() {
  Foo foo = Bar(10); //prints 'Hi there'
}

Hope it helps!

UPDATE

You can also call the super constructor and add other statements to the child constructor using this way -

class Foo {
  int superValue;

  Foo(this.superValue);
}

class Bar extends Foo { 
  int value;

  Bar(int x) : super(x) {
    value = x;
    print("Hi there");
  }
}

void main() {
  Foo foo = Bar(10);
}
like image 161
thedarthcoder Avatar answered Oct 30 '25 23:10

thedarthcoder