Let's look at a simple case first:
In fact, for each member variable, dart will complete the default encapsulation of it
void main() {
var p = Point("a");//这个默认是有一个set
print(p.aaa);//这里默认是有一个get只是我们看不到而已
}
class Point {
late String aaa;
Point(this.aaa);
}
If we remove the get operation:
it cannot be accessed, and the security will be improved at this time, and the flexibility will be higher if there is a get method
//get set的使用方法:
void main() {
var p = Point();
p.Point1 = "dandaoya";
//print(p.Point1);//这里无法被访问,去掉get后安全性会得到控制
}
class Point {
late String _name;
set Point1(String value) {
_name = value;
}
//如果我们去掉了get的操作,那么就无法被访问了;
// String get Point1 {
// return "my name is ${_name}";
// }
}
void main() {
var rect = Rectangle(3, 4, 20, 15);
assert(rect.left == 3);
print('${rect.left}');
rect.right = 12;
print('${rect.left}');
assert(rect.left == -8);
}
class Rectangle {
late double left, top, width, height;
Rectangle(this.left, this.height, this.width, this.top);
double get right => left + width; //创建get set方法他们可以在赋值或者取值的时候进行一个计算操作
//扩展了对属性的直接操作
set right(double value) {
left = value - width;
}
double get bottom => top + height;
set bottom(double value) => top = value - height;
}