Skip to content

构造函数

如果不显示声明构造函数,则会调用默认构造函数。默认构造函数没有参数

dart
class Point {
  int x, y;
  Point(this.x, this.y);

  @override
  String toString() {
    return '$x, $y';
  }
}

final p = Point(1, 2);
print(p);

初始化列表

构造函数中的:表示一个初始化器,它先于构造函数执行,用来初始化实例变量

dart
class Point {
  int x, y;
  Map position1, position2;
  Point(this.x, this.y)
      : position1 = {'x': x, 'y': y},
        position2 = {'x': x + 10, 'y': y + 10} {
    print('In Point(): ($x, $y, $position1, $position2)');
  }

  @override
  String toString() {
    return '$x, $y, $position1, $position2';
  }
}

命名构造函数

dart
class Point {
  int x, y;
  Map position1, position2;
  Point.fromJson(Map json)
      : x = json['x'],
        y = json['y'],
        position1 = {'x': json['x'], 'y': json['y']},
        position2 = {'x': json['x'] * 2, 'y': json['y'] * 2} {
    print('In Point.fromJson(): ($x, $y, $position1, $position2)');
  }

  @override
  String toString() {
    return '$x, $y, $position1, $position2';
  }
}

重定向构造函数

dart
class Point {
  int x, y;
  Map position1, position2;
  Point(this.x, this.y)
      : position1 = {'x': x, 'y': y},
        position2 = {'x': x + 10, 'y': y + 10} {
    print('In Point(): ($x, $y, $position1, $position2)');
  }

  Point.fromJson(Map json) : this(json['x'], json['y']);

  @override
  String toString() {
    return '$x, $y, $position1, $position2';
  }
}

callable

dart
class Phone {
  call(String phone) {
    print('phone number is $phone');
  }
}

var phone = Phone();
phone('911');

MIT License