Learn how to create and use constructors in Dart with simple examples and real-life comparisons.
A constructor is a special method in a class that is automatically called when you create an object. It helps to initialize the object’s properties with values.
Imagine you want to build a custom toy car. When you order the toy car, you tell the builder its color and model. The builder uses this information right away to create your toy car exactly how you want it. The builder listening to your instructions is like a constructor in programming — it sets up the object immediately when it’s created.
class ToyCar {
String color;
String model;
// Constructor
ToyCar(String c, String m) {
color = c;
model = m;
}
void display() {
print("This is a $color $model toy car.");
}
}
void main() {
ToyCar myToy = ToyCar("blue", "sports");
myToy.display(); // Output: This is a blue sports toy car.
}
In this example, the ToyCar class has a constructor that takes two parameters c and m, and sets the object’s color and model when it is created.
class ToyCar {
String color;
String model;
// Constructor shorthand
ToyCar(this.color, this.model);
void display() {
print("This is a $color $model toy car.");
}
}
void main() {
ToyCar myToy = ToyCar("red", "convertible");
myToy.display(); // Output: This is a red convertible toy car.
}
Dart allows a shorter way to write constructors using this.propertyName directly in the constructor parameter list.
Sometimes, you want more than one way to create an object. Named constructors help you do that.
class ToyCar {
String color;
String model;
ToyCar(this.color, this.model);
// Named constructor
ToyCar.redSports() {
color = "red";
model = "sports";
}
void display() {
print("This is a $color $model toy car.");
}
}
void main() {
ToyCar car1 = ToyCar("green", "sedan");
car1.display(); // Output: This is a green sedan toy car.
ToyCar car2 = ToyCar.redSports();
car2.display(); // Output: This is a red sports toy car.
}
Here, ToyCar.redSports() is a named constructor that creates a red sports toy car without needing to pass arguments.
Constructors make it easy to create objects with initial values right away, keeping your code clean and organized.