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
Replay: real traced execution (multi-file project)
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}');
}
a ← Point(x: 3, y: 4)
9void main() {10 var a = Point(3, 4);11 var b = Point.origin();values this stepPoint(x: 3, y: 4)acall ← Point.origin()
10var a = Point(3, 4);11var b = Point.origin();12var c = Point.diagonal(5);values this stepPoint.origin()callinit list ← x = 0, y = 0
4Point(this.x, this.y);5Point.origin() : x = 0, y = 0;6Point.diagonal(int n) : x = n, y = n;values this stepx = 0, y = 0init listb ← Point(x: 0, y: 0)
10var a = Point(3, 4);11var b = Point.origin();12var c = Point.diagonal(5);values this stepPoint(x: 0, y: 0)bcall ← Point.diagonal(5)
11var b = Point.origin();12var c = Point.diagonal(5);13print('${a.x},${a.y} ${b.x},${b.y} ${c.x},${c.y}');values this stepPoint.diagonal(5)callinit list ← x = 5, y = 5
5 Point.origin() : x = 0, y = 0;6 Point.diagonal(int n) : x = n, y = n;7}values this stepx = 5, y = 5init list5nc ← Point(x: 5, y: 5)
11var b = Point.origin();12var c = Point.diagonal(5);13print('${a.x},${a.y} ${b.x},${b.y} ${c.x},${c.y}');values this stepPoint(x: 5, y: 5)cprint('${a.x},${a.y} ${b.x},${b.y} ${c.x},${c.y}');
12 var c = Point.diagonal(5);13 print('${a.x},${a.y} ${b.x},${b.y} ${c.x},${c.y}');14}output3,4 0,0 5,5values this stepPoint(3, 4)aPoint(0, 0)bPoint(5, 5)c
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.