Classes, Enums, Extensions
Constructors
Generative and Named
A generative constructor with this.x assigns positional arguments to final fields. Named constructors give a class extra ways to build itself, with an initializer list : x = ..., y = ... setting the fields before the body runs.
Program
Play the program to build a Point three different ways.
constructors.dart
class Point {
final int x;
final int y;
Point(this.x, this.y);
Point.origin() : x = 0, y = 0;
Point.diagonal(int n) : x = n, y = n;
}
void main() {
var a = Point(3, 4);
var b = Point.origin();
var c = Point.diagonal(5);
print('${a.x},${a.y} ${b.x},${b.y} ${c.x},${c.y}');
}
generative
`Point(this.x, this.y)` assigns straight to `final` fields from positional arguments.
named constructor
`Point.origin()` and `Point.diagonal(n)` are extra named ways to build a `Point`.
initializer list
`: x = 0, y = 0` runs before the body and is required when `final` fields need values.