Dart by Example: Constructors

  1. import 'dart:math';
  2. class Position {
  3. int x;
  4. int y;
  5. // A simple constructor
  6. Position(this.x, this.y);
  7. // Additional constructors can be defined using named constructors
  8. Position.atOrigin() {
  9. x = 0;
  10. y = 0;
  11. }
  12. // Factory constructors
  13. factory Position.fromMap(Map m) {
  14. return new Position(m['x'], m['y']);
  15. }
  16. String toString() => "[$x, $y]";
  17. }
  18. main() {
  19. print(new Position(30, 40));
  20. print(new Position.atOrigin());
  21. print(new Position.fromMap({'x': 4, 'y': 100}));
  22. }
  23.  
  1. $ dart constructors.dart
  2. [30, 40]
  3. [0, 0]
  4. [4, 100]

by @jryanio | source | license