Getters, Setters, and Privacy
Prerequisites: Constructors
Dart lets you control how fields are read and changed, and hide implementation details.
Getters — computed properties
A getter looks like a field from the outside but calculates its value when read:
class Rectangle {
double width;
double height;
Rectangle(this.width, this.height);
double get area => width * height;
bool get isSquare => width == height;
}
void main() {
final rect = Rectangle(4, 5);
print(rect.area);
rect.width = 5;
print(rect.area);
print(rect.isSquare);
}
20.0
25.0
true
area is always correct, because it's recalculated from the current
width and height.
Privacy with underscores
Names starting with _ are private to the library (the file). Pair
a private field with a public getter to make something read-only from
outside:
class Counter {
int _count = 0;
int _step = 1;
int get count => _count;
set step(int value) {
if (value <= 0) throw ArgumentError('step must be positive');
_step = value;
}
void increment() => _count += _step;
}
void main() {
final c = Counter();
c.step = 5;
c.increment();
c.increment();
print(c.count);
}
10
countcan be read but not assigned — there's no setter.set step(int value)is a setter with validation. Callers writec.step = 5, like assigning a field.
Dart privacy is per file, not per class: code elsewhere in the same
file can still see _count. In practice, one main class per file makes
this behave like class privacy.
Common mistakes
- Writing getters and setters that just read and write a field. Dart doesn't need them — use a public field, and switch to a getter/setter later if you need logic; callers won't have to change.