How do I call on the super class' constructor and other statements in Dart?

13,180

Solution 1

You can call super in this way:

abstract class Animal {
  String name;
  Animal (String this.name);
}

class Dog extends Animal {
  Dog() : super('Spot') {
    print("Dog was created");
  }
}

void main() {
  var d = new Dog(); // Prints 'Dog was created'.
  print(d.name);     // Prints 'Spot'.
}

Solution 2

If you want execute code before the super you can do it like that:

abstract class Animal {
  String name;
  Animal (this.name);
}

class Cat extends Animal {
  String breed;

  Cat(int i):
    breed = breedFromCode(i),
    super(randomName());

  static String breedFromCode(int i) {
    // ...
  }

  static String randomName() {
    // ...
  }
}

Solution 3

In Flutter (Dart), if we have a

class Bicycle {
  int gears;

  Bicycle(this.gears); // constructor
}

and a child inheriting from it

class ElectricBike extends Bicycle {
  int chargingTime;
}

We can pass the parent constructor input parameter gears as such:

class ElectricBike extends Bicycle {
  int chargingTime;

  
  ElectricBike(int gears, this.chargingTime) : super(gears);
}

Please note the use of : super(<parents parameters).

Share:
13,180
corgrath
Author by

corgrath

Updated on June 15, 2022

Comments

  • corgrath
    corgrath about 2 years

    Given this code:

    abstract class Animal {
    
            String name;
    
            Animal (String this.name) {
            }
    
    }
    
    class Dog extends Animal {
    
            // Why does this fail
            Dog() {
                super("Spot");
                print("Dog was created");
            }
    
            // Compared to this
            // Dog() : super("Spot");
    
    }
    

    According to multiple docs:

    You can call the super class' constructor with the following syntax:

    Dog() : super("Spot");
    

    I assume this is some kind of a shortcut syntax to quickly call the super class' constructor. But what if I also want to do additional things in the Dog's constructor, such as calling print.

    Why doesn't this work, and what is the proper way to write the code?

    // Why does this fail
    Dog() {
        super("Spot");
        print("Dog was created");
    }