One of the powerful features Dart offers is the ability to assign default values to parameters in constructors. This feature ensures that your objects are initialized properly even when some arguments are not provided during their creation. It brings flexibility to object instantiation, making your code more robust and maintainable.
Consider a scenario where you want to define a default color for all cars unless specified otherwise. You can achieve this by assigning a default value to the color parameter in the constructor:
class Car {
String brand;
String model;
String color;
// Constructor with a default 'color' value of "white"
Car(this.brand, this.model, [this.color = "white"]) {
print('New Car: $brand $model, Color: $color');
}
}
In this modified version, when instantiating a Car object, if the color is not provided, the color will automatically be set to "white". This feature simplifies the initialization process, particularly when dealing with optional properties that have sensible default values:
var defaultCar = Car("Hyundai", "Elantra");
// Prints: New Car: Hyundai Elantra, Color: white
var redCar = Car("Honda", "Civic", "red");
// Prints: New Car: Honda Civic, Color: red
Notice how the color parameter is enclosed in square brackets [], which denotes that it is an optional parameter. Dart allows you to provide default values for these optional parameters, ensuring a high degree of flexibility while still guaranteeing object completeness upon creation.