Skip to Content

Getters và Setters trong Dart

1. Giới thiệu

Getters và setters cho phép kiểm soát cách đọc và ghi thuộc tính của class.

2. Getter

class Circle { double radius; Circle(this.radius); // Getter - computed property double get area => 3.14159 * radius * radius; double get circumference => 2 * 3.14159 * radius; double get diameter => radius * 2; } void main() { var circle = Circle(5); print(circle.area); // 78.53975 print(circle.circumference); // 31.4159 }

3. Setter

class Person { String _name = ''; // Getter String get name => _name; // Setter với validation set name(String value) { if (value.isNotEmpty) { _name = value; } } } void main() { var person = Person(); person.name = 'Alice'; print(person.name); // Alice person.name = ''; // Không thay đổi vì rỗng print(person.name); // Alice }

4. Private fields với Getter/Setter

class BankAccount { double _balance = 0; double get balance => _balance; set balance(double value) { if (value >= 0) { _balance = value; } else { throw ArgumentError('Balance cannot be negative'); } } void deposit(double amount) { if (amount > 0) _balance += amount; } }

5. Read-only property

class User { final String _id; String name; User(this._id, this.name); // Chỉ có getter, không có setter String get id => _id; } void main() { var user = User('123', 'Alice'); print(user.id); // 123 // user.id = '456'; // Error! Không có setter }

6. Computed properties

class Rectangle { double width, height; Rectangle(this.width, this.height); double get area => width * height; double get perimeter => 2 * (width + height); bool get isSquare => width == height; }

7. Lazy initialization

class ExpensiveResource { List<int>? _data; List<int> get data { _data ??= _loadData(); return _data!; } List<int> _loadData() { print('Loading data...'); return [1, 2, 3, 4, 5]; } }

8. Validation trong Setter

class Temperature { double _celsius = 0; double get celsius => _celsius; set celsius(double value) { if (value < -273.15) { throw ArgumentError('Below absolute zero!'); } _celsius = value; } double get fahrenheit => _celsius * 9/5 + 32; set fahrenheit(double value) { celsius = (value - 32) * 5/9; } }

📝 Tóm tắt

  • get cho computed/derived properties
  • set cho validation khi gán giá trị
  • Chỉ có getter = read-only
  • Kết hợp với _ để encapsulation
  • Arrow syntax cho getter đơn giản
Last updated on