1、this
使用this.propertyName,快捷属性赋值
class MyColor {
int red;
int green;
int blue;
MyColor(this.red, this.green, this.blue);
}
命名参数以及可选参数都可以
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、初始化列表
可以在构造函数主体执行之前进行一些设置,可以设置断言
NonNegativePoint(this.x, this.y)
: assert(x >= 0),
assert(y >= 0) {
print('I just made a NonNegativePoint: ($x, $y)');
}
3、构造函数
允许类有多个构造函数,
(1)命名构造函数
class Point {
double x, y;
Point(this.x, this.y);
Point.origin() {
x = 0;
y = 0;
}
}
final myPoint = Point.origin();
(2)工厂构造函数,允许返回子类型或者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)重定向构造函数
在同一个类中,重定向到另一个构造函数,没有函数体的构造函数
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)不可变对象构造函数
如果您的类产生的对象永不改变,定义一个const构造函数,并确保所有实例变量都是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
//控制一个属性
class MyClass {
int _aProperty = 0;
int get aProperty => _aProperty;
set aProperty(int value) {
if (value >= 0) {
_aProperty = value;
}
}
}