inheritanceconstructordartsuperclassextends

How do I call a super constructor in Dart?


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


Solution

  • 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);  
    
      Baz.named(int c, int d) : super.named(c, d);  
    }
    

    If you want to initialize instance variables in the subclass, the super() call must be last in an initializer list.

    class CBar extends Foo {
      int c;
    
      CBar(int a, int b, int cParam) :
        c = cParam,
        super(a, b);
    }
    

    You can read about the motivation behind this super() call guideline on /r/dartlang.