thumbnail

Named Constructor In Dart

Published on 29 March 2020
Last Updated on 29 March 2020

Named constructors allow a programmer to implement multiple constructors with different names that can have the ability to initialize fields with different values and are identified with different names.

Constructors are not inherited by the child class, this means named constructors are also not inherited by the child class. A programmer must explicitly define a named constructor in a child class.

Program that demonstrates use of Named Constructors in Dart

// program to named constructor

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

  printName() {
    print('name of animal is ${name}');
  }

  Animal.cat() {
    name = 'cat';
  }
  Animal.dog() {
    name = 'dog';
  }
  Animal.mouse() {
    name = 'mouse';
  }
}

main(List<String> args) {
  // creating custom Animal objects using named constructors
  Animal.cat()..printName();
  Animal.dog()..printName();
  Animal.mouse()..printName();
}

Above program produces following output:

colorA.red : 1
colorA.green: 2
colorA.blue: 3

colorB.red : 1
colorB.green: 2
colorB.blue: 3

We hope that you have found this guide useful for learning named constructors in Dart.