1、this
使用this.propertyName劳澄,快捷屬性賦值
class MyColor {
? int red;
? int green;
? int blue;
? MyColor(this.red, this.green, this.blue);
}
命名參數(shù)以及可選參數(shù)都可以
MyColor({this.red = 0, this.green = 0, this.blue = 0});
MyColor([this.red = 0, this.green = 0, this.blue = 0]);
MyColor({this.red, this.green, this.blue});
2秒拔、初始化列表
可以在構(gòu)造函數(shù)主體執(zhí)行之前進(jìn)行一些設(shè)置作谚,可以設(shè)置斷言
NonNegativePoint(this.x, this.y)
? ? : assert(x >= 0),
? ? ? assert(y >= 0) {
? print('I just made a NonNegativePoint: ($x, $y)');
}
3双吆、構(gòu)造函數(shù)
允許類有多個(gè)構(gòu)造函數(shù)回官,
(1)命名構(gòu)造函數(shù)
class Point {
? double x, y;
? Point(this.x, this.y);
? Point.origin() {
? ? x = 0;
? ? y = 0;
? }
}
final myPoint = Point.origin();
(2)工廠構(gòu)造函數(shù)侄泽,允許返回子類型或者null
class Square extends Shape {}
class Circle extends Shape {}
class Shape {
? Shape();
? factory Shape.fromTypeName(String typeName) {
? ? if (typeName == 'square') return Square();
? ? if (typeName == 'circle') return Circle();
? ? print('I don\'t recognize $typeName');
? ? return null;
? }
}
(3)重定向構(gòu)造函數(shù)
在同一個(gè)類中艰垂,重定向到另一個(gè)構(gòu)造函數(shù)泡仗,沒有函數(shù)體的構(gòu)造函數(shù)
class Automobile {
? String make;
? String model;
? int mpg;
? // The main constructor for this class.
? Automobile(this.make, this.model, this.mpg);
? // Delegates to the main constructor.
? Automobile.hybrid(String make, String model) : this(make, model, 60);
? // Delegates to a named constructor
? Automobile.fancyHybrid() : this.hybrid('Futurecar', 'Mark 2');
}
(4)不可變對象構(gòu)造函數(shù)
如果您的類產(chǎn)生的對象永不改變,定義一個(gè)const構(gòu)造函數(shù)猜憎,并確保所有實(shí)例變量都是final娩怎。
class ImmutablePoint {
? const ImmutablePoint(this.x, this.y);
? final int x;
? final int y;
? //static const ImmutablePoint origin = ImmutablePoint(0, 0);
}
4、Getters and setters
//控制一個(gè)屬性
class MyClass {
? int _aProperty = 0;
? int get aProperty => _aProperty;
? set aProperty(int value) {
? ? if (value >= 0) {
? ? ? _aProperty = value;
? ? }
? }
}