Dart Properties in Depth
A getter reads a value that looks like a field. A setter controls what happens when code assigns to that name.
A getter and setter that convert
The temperature stores Celsius in a private field. The Fahrenheit getter converts on read and the Fahrenheit setter converts on write.
class Temperature {
double _celsius = 0;
double get celsius => _celsius;
set celsius(double value) {
_celsius = value;
}
double get fahrenheit => _celsius * 9 / 5 + 32;
set fahrenheit(double value) {
_celsius = (value - 32) * 5 / 9;
}
}
void main() {
final t = Temperature();
t.celsius = 100;
print(t.fahrenheit);
t.fahrenheit = 32;
print(t.celsius);
}A setter that clamps a value
The price setter stores 0 when the given value is negative. The prints show the stored value each time.
class Product {
double _price = 0;
double get price => _price;
set price(double value) {
if (value < 0) {
_price = 0;
} else {
_price = value;
}
}
}
void main() {
final p = Product();
p.price = 25;
print(p.price);
p.price = -10;
print(p.price);
}A computed getter with no setter
The area getter multiplies width by height on every read. Nothing is stored, and there is no setter to assign to.
class Rectangle {
final double width;
final double height;
Rectangle(this.width, this.height);
double get area => width * height;
}
void main() {
final r = Rectangle(4, 3);
print(r.area);
}Example
class Temperature {
double _celsius = 0;
double get celsius => _celsius;
set celsius(double value) {
_celsius = value;
}
double get fahrenheit => _celsius * 9 / 5 + 32;
set fahrenheit(double value) {
_celsius = (value - 32) * 5 / 9;
}
}
void main() {
final t = Temperature();
t.fahrenheit = 212;
print(t.celsius);
t.celsius = 25;
print(t.fahrenheit);
print(t.celsius);
}Key points
- A getter is declared with get and takes no arguments.
- A setter is declared with set and takes one value.
- A private field often stores the real value behind the pair.
- A setter can change the value before storing it.
- A getter with no setter is read-only from outside the class.
- Code using the pair reads and writes it like a plain field.
In this example, assigning 212 to fahrenheit runs the setter, which stores 100 in the private Celsius field. Reading celsius then prints 100.0. Assigning 25 to celsius stores 25 directly, and the fahrenheit getter converts it to 77.0.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท DartPad
Exercise
What happens when code assigns to a name that has a getter but no setter?