getter 和 setter
void main() {
var cat = new Cat();
print("Is cat hungry? ${cat.isHungry}"); // Is cat hungry? true
print("Is cat cuddly? ${cat.isCuddly}"); // Is cat cuddly? false
print("Feed cat.");
cat.isHungry = false;
print("Is cat hungry? ${cat.isHungry}"); // Is cat hungry? false
print("Is cat cuddly? ${cat.isCuddly}"); // Is cat cuddly? true
}
class Cat {
bool _isHungry = true;
bool get isCuddly => !_isHungry;
bool get isHungry => _isHungry;
bool set isHungry(bool hungry) => this._isHungry = hungry;
}
Dart 类 getter 和 setter 允许 API 封装对象状态更改。
请参阅此处的 dartpad 示例: https : //dartpad.dartlang.org/c25af60ca18a192b84af6990f3313233