Getters and setters
Getter and setter methods provide read and write access to internal object state. When calling a getter or setter, omit the trailing parentheses. Define getters and setters using the
get
and set
keywords.class Rectangle {
num left, top, width, height;
Rectangle(this.left, this.top, this.width, this.height);
num get right() => left + width;
set right(num value) => left = value - width;
num get bottom() => top + height;
set bottom(num value) => top = value - height;
}
Use explicit getters and setters just like you would use the generated getters and setters from instance variables.
var rect = new Rectangle(3, 4, 20, 15);
assert(rect.left == 3);
rect.right = 12;
assert(rect.left == -8);
With getters and setters, you can start with instance variables, later wrapping them with methods, all without changing client code