Dart by Example: Constructors
1. import 'dart:math';
3. class Position {
4. int x;
5. int y;
7. // A simple constructor
8. Position(this.x, this.y);
10. // Additional constructors can be defined using named constructors
11. Position.atOrigin() {
12. x = 0;
13. y = 0;
14. }
16. // Factory constructors
17. factory Position.fromMap(Map m) {
18. return new Position(m['x'], m['y']);
19. }
21. String toString() => "[$x, $y]";
22. }
24. main() {
25. print(new Position(30, 40));
26. print(new Position.atOrigin());
27. print(new Position.fromMap({'x': 4, 'y': 100}));
28. }
1. $ dart constructors.dart
2. [30, 40]
3. [0, 0]
4. [4, 100]
by @jryanio | source | license