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