Dart Constructors
A named constructor is a constructor with an extra name after the class name. A class can offer several named constructors for different starting values.
A named constructor for a puppy
A named constructor adds a name after the class name, as in Dog.puppy. The initializer list after the colon sets age to 0.
class Dog {
String name;
int age;
Dog(this.name, this.age);
Dog.puppy(this.name) : age = 0;
}
void main() {
var pip = Dog.puppy('Pip');
print(pip.name);
print(pip.age);
}A second named constructor
A class can hold more than one named constructor. Dog.senior starts its object at age 12.
class Dog {
String name;
int age;
Dog(this.name, this.age);
Dog.puppy(this.name) : age = 0;
Dog.senior(this.name) : age = 12;
}
void main() {
var duke = Dog.senior('Duke');
print(duke.name);
print(duke.age);
}An initializer list on its own
An initializer list can stand in a plain constructor too. Box sets size to 1 before any code reads the field.
class Box {
int size;
Box() : size = 1;
}
void main() {
var box = Box();
print(box.size);
}Three constructors, three ages
Three constructors start three dogs in this program. The printed ages show 4, 0, and 12 in order.
class Dog {
String name;
int age;
Dog(this.name, this.age);
Dog.puppy(this.name) : age = 0;
Dog.senior(this.name) : age = 12;
}
void main() {
var dogs = [Dog('Rex', 4), Dog.puppy('Pip'), Dog.senior('Duke')];
for (var dog in dogs) {
print('${dog.name} is ${dog.age}');
}
}Example
class Cat {
String name;
int age;
Cat(this.name, this.age);
Cat.kitten(this.name) : age = 0;
Cat.stray() : name = 'Unknown', age = 1;
String get label => '$name, age $age';
}
void main() {
var milo = Cat('Milo', 3);
var tiny = Cat.kitten('Tiny');
var stray = Cat.stray();
print(milo.label);
print(tiny.label);
print(stray.label);
}Key points
- Write a named constructor with the class name, a dot, and the extra name.
- An initializer list sits after a colon and sets fields before the object is used.
- Each named constructor can fill different fields with fixed values.
- A plain constructor and named constructors can live in the same class.
- A named constructor call looks like a method call on the class name.
In this example, the class Cat has one plain constructor and two named constructors. Cat.kitten fills only the name, and its initializer list sets age to 0. Cat.stray takes no values, and its initializer list sets both fields. The getter label prints each cat with its age, and the three ages differ.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท DartPad
Exercise
What does Dog.puppy('Pip') call?