Constructor is the special method that runs when a class creates a new object. Dart gives you several ways to write one — short-form constructors, named constructors, initializer lists, and more.
dart
class Point {
final double x;
final double y;
Point(this.x, this.y);
Point.origin()
: x = 0,
y = 0;
Point.vertical(double yValue)
: x = 0,
y = yValue;
}
void main() {
final p1 = Point(2, 3);
final p2 = Point.origin();
final p3 = Point.vertical(10);
print('p1: ${p1.x}, ${p1.y}');
print('p2: ${p2.x}, ${p2.y}');
print('p3: ${p3.x}, ${p3.y}');
}Point(this.x, this.y) is a normal constructor. Point.origin() and Point.vertical() are named constructors, and their names describe the purpose of the object they create.
You should see
p1: 2.0, 3.0 p2: 0.0, 0.0 p3: 0.0, 10.0