Getters & Setters
In Dart, reading obj.x or writing obj.x = v doesn't have to touch a field directly. Getters and setters are methods that look like fields from the outside. Every public field already comes with an implicit getter (and a setter, if it isn't final), so you can start with a plain field and switch to a computed property later without changing any calling code.
Computed getters
A getter is declared with get and has no parameter list:
class Circle {
double radius;
Circle(this.radius);
double get diameter => radius * 2;
double get area => 3.14159 * radius * radius;
bool get isLarge => radius > 10;
}
void main() {
final c = Circle(3);
print(c.diameter);
print(c.area.toStringAsFixed(2));
c.radius = 12;
print(c.isLarge);
}6.0
28.27
true
Getters are recomputed on every access, so they always reflect the current state. Use them for cheap, side-effect-free values; use a method (calculateTax()) when the work is expensive or needs arguments.
Setters with validation
A setter is declared with set and takes exactly one parameter. A common pattern is a private field (_name) plus a public getter/setter pair that guards it:
class Thermostat {
double _target = 21;
double get target => _target;
set target(double value) {
if (value < 10 || value > 30) {
throw RangeError.range(value.round(), 10, 30, 'target');
}
_target = value;
}
}
void main() {
final t = Thermostat();
t.target = 24.5;
print(t.target);
try {
t.target = 45;
} on RangeError catch (e) {
print(e.message);
print('still ${t.target}');
}
t.target += 1; // uses the getter, then the setter
print(t.target);
}24.5
Invalid value
still 24.5
25.5
Read-only properties
Expose a getter without a setter and the property becomes read-only from outside, while the class can still change the private field:
class BankAccount {
final String owner;
int _balance = 0;
final List<String> _history = [];
BankAccount(this.owner);
int get balance => _balance;
List<String> get history => List.unmodifiable(_history);
void deposit(int amount) {
_balance += amount;
_history.add('+$amount');
}
}
void main() {
final acc = BankAccount('Nhung')
..deposit(100)
..deposit(40);
print(acc.balance);
print(acc.history);
try {
acc.history.add('+1000000');
} on UnsupportedError catch (e) {
print('blocked: ${e.message}');
}
}140
[+100, +40]
blocked: Cannot add to an unmodifiable list
Returning List.unmodifiable(...) prevents callers from mutating the internal list through the getter — a detail that's easy to forget.
Trying to assign to a getter-only property is a compile error:
class Order {
final int _total = 99;
int get total => _total;
}
void main() {
final o = Order();
o.total = 5;
}example.dart:8:5: Error: The setter 'total' isn't defined for the class 'Order'.
- 'Order' is from 'example.dart'.
Try correcting the name to the name of an existing setter, or defining a setter or field named 'total'.
o.total = 5;
^^^^^
Error: AOT compilation failed
Bad state: Generating AOT kernel dill failed!
Don't write trivial getters and setters
Coming from Java, you might write getName()/setName() for every field. In Dart that's unnecessary noise — a public field is already a property:
// Not idiomatic
class Person {
String _name;
Person(this._name);
String get name => _name;
set name(String v) => _name = v;
}
// Idiomatic: identical API for callers
class Person {
String name;
Person(this.name);
}If you later need validation, convert the field to a getter/setter pair. Callers using person.name won't notice.
Top-level and static getters
Getters and setters aren't limited to instances:
int _requests = 0;
int get requestCount => _requests; // top-level getter
class Config {
static bool get isDebug => const bool.fromEnvironment('DEBUG');
}| Declaration | Read | Write |
|---|---|---|
String name; |
✅ | ✅ |
final String name; |
✅ | ❌ |
String get name => …; |
✅ | ❌ |
String get name + set name(String v) |
✅ | ✅ (custom logic) |
late final String name; |
✅ | Once |
Tip: A getter and its setter should use the same type, and reading right after writing should usually return the value you wrote. Surprising properties make code hard to reason about.
Test yourself
How many parameters does a setter take?
- None
- Exactly one
- One or more
- Any number
What does t.target += 1 do when target is a getter/setter pair?
- Calls only the setter
- Calls the getter, adds 1, then calls the setter
- Compile error
- Modifies the private field directly
Why is writing getName()/setName() for every field discouraged in Dart?
- They are slower
- Public fields already act as properties, and you can switch to a getter later without changing callers
- Dart forbids methods starting with get
- Setters can't be private