In Object-Oriented Programming, getters and setters are special methods that provide access to an object’s properties.
Each property has its implicit getters and setters. You can create your own getters and setters if needed.
class Sale { final int id; final String name; final String status; double amount; double get exchangedAmount{ return amount*1.2; } set exchangedAmount(double rate){ amount = amount*rate; } String get statusText { Map<String, String> map = { 'draft': 'Draft', 'sent': 'Sent', 'sale': 'Sale', }; if (map.containsKey(status)) { return map[status]; } return status; } Sale(this.id, this.name, this.status, this.amount); }
class Person { String _name; String get name => _name; set name(String value) => _name = value; } void main() { var person = Person(); person.name = "John"; print(person.name); // Output: John }
class BankAccount { num _balance; BankAccount(this._balance); num get balance => _balance; set balance(num value) { if (value < 0) { throw "Balance cannot be negative"; } _balance = value; } } void main() { var account = BankAccount(1000); account.balance = 500; print(account.balance); // Output: 500 account.balance = -500; // Throws an exception }