-->

How do I call a super constructor in Dart?

2019-02-11 15:01发布

问题:

How do I call a super constructor in Dart? Is it possible to call named super constructors?

回答1:

Yes it is, the syntax is close to C#, here is an example with both default constructor and named constructor:

class Foo {
  Foo(int a, int b) {
    //Code of constructor
  }

  Foo.named(int c, int d) {
    //Code of named constructor
  }
}

class Bar extends Foo {
  Bar(int a, int b) : super(a,b);
}

class Baz extends Foo {
  Baz(int c, int d) : super.named(c,d);  
}


回答2:

Can I call a private constructor of the superclass?

Yes, but only if the superclass and the subclass you are creating are in the same library. (Since private identifiers are visible across the whole library they are defined in). Private identifiers are those that start with underscore.

class Foo {    
  Foo._private(int a, int b) {
    //Code of private named constructor
  }
}

class Bar extends Foo {
  Bar(int a, int b) : super._private(a,b);
}


回答3:

As dart supports implementing a class as interface (Implicit interfaces), you can't call the parent constructor if you implemented it you should use extends. If you use implements change it to extends and use Eduardo Copat's Solution.