Dart
Getters and setters
Learn controlled access with get and set.
get and set
Dart offers getters and setters for controlled access to private fields. They are written with the get and set keywords; the call uses no parentheses.
Example: double get balance => _balance; set balance(double value) { if (value < 0) return; _balance = value; }. Here balance is a readable and writable accessor. Reading looks like a.balance and writing like a.balance = 100. The condition inside the setter blocks negative values. This shape is a clean way to add validation without exposing the field directly.
Validation with a setter
A setter intercepts writes; this lets you validate values. When an invalid value is given, the assignment is blocked or corrected.
Example: set balance(double value) { if (value < 0) return; _balance = value; }. Here, if a negative value is given, return stops the operation and _balance stays unchanged. This prevents user mistakes; the object stays consistent. Read only fields have no setter; the field then becomes read only and cannot be changed from outside.
Exercise Add a getter and setter to Account
Define the Account class; add a private double _balance field and an Account(this._balance) constructor. Write a double get balance => _balance; getter and a set balance(double value) { if (value < 0) return; _balance = value; } setter. In main, create an instance with var a = Account(100);, print with print(a.balance), update with a.balance = 200 and print again with print(a.balance).
Show example solution
// Define the Account class
class Account {
double _balance;
Account(this._balance);
double get balance => _balance;
set balance(double value) {
if (value < 0) return;
_balance = value;
}
}
void main() {
var a = Account(100);
print(a.balance);
a.balance = 200;
print(a.balance);
}
Test yourself
-
Complete the getter declaration
double ____ balance => _balance;
Show answer
double get balance => _balance;
-
What does set balance(double value) do?
- Only reads the value
- Defines a static field
- Wraps the write with validation
- Calls the constructor
Show answer
Wraps the write with validation — A setter intercepts writes and adds validation.
-
Match the accessor parts
- get
- Read accessor
- set
- Write accessor
- _balance
- Private field
Next lesson: final and const fields