On this page10 sections
Lecture 035: Getters & Setters
| Day | 12: Singleton, Getters & Static |
| Lecture | 035 of 057 |
| Estimated video length | 12 min |
| Target | Dart 3.12 |
| Level | Beginner |
A rectangle's area isn't stored anywhere; it's worked out from the width and height. A getter looks like a field but calculates its value on the spot. A setter looks like assigning to a field, but runs code first, so it can reject bad values.
Contents
Prerequisites · Objectives · Lesson · Code Examples · Common Mistakes · Practice Questions · Answers · Takeaways
Prerequisites
Lectures 030–033 (classes, constructors and this).
Learning Objectives
- Write a getter with
get - Use getters for values calculated from other fields
- Write a setter with
setthat checks values - Pair a private field with a getter and setter
- Know when to use a getter instead of a method
1. Getters: Calculated Fields
class Rectangle {
double width;
double height;
Rectangle(this.width, this.height);
double get area => width * height;
double get perimeter => 2 * (width + height);
bool get isSquare => width == height;
}
var r = Rectangle(3, 4);
print(r.area); // 12.0 (no brackets)
print(r.perimeter); // 14.0
print(r.isSquare); // false
r.width = 4;
print(r.area); // 16.0 (always up to date)
print(r.isSquare); // truedouble get area => ... defines a getter: a return type, the word get, a name, and no
brackets. You read it like a field (r.area), but it's recalculated each time, so it can never
be out of date.
2. Setters: Assignments That Check
A setter runs when you assign to the name. Pair it with a private field (starting with _)
that holds the real value:
class Temperature {
double _celsius = 0;
double get celsius => _celsius;
set celsius(double value) {
if (value < -273.15) {
print('Below absolute zero, ignored: $value');
return;
}
_celsius = value;
}
double get fahrenheit => _celsius * 9 / 5 + 32;
set fahrenheit(double f) => celsius = (f - 32) * 5 / 9;
}
var t = Temperature();
t.celsius = 25; // runs the setter
print(t.fahrenheit); // 77.0
t.fahrenheit = 212; // converts, then uses the celsius setter
print(t.celsius); // 100.0
t.celsius = -300; // Below absolute zero, ignored: -300.0
print(t.celsius); // 100.0 (unchanged)A setter has the word set, a name and exactly one parameter. It never returns a value.
3. Getter or Method?
| Use a getter when… | Use a method when… |
|---|---|
| it's a property of the object (area, isEmpty, fullName) | it does something (save, send, calculate with arguments) |
| it's quick to work out | it's slow or has side effects |
| it needs no arguments | it needs arguments |
You've used built-in getters all along: list.length, text.isEmpty, list.first.
Code Examples
Example 1: A Password Field
class Password {
String _value = '';
set value(String text) {
if (text.length < 8) {
print('Rejected: "$text" is too short');
return;
}
_value = text;
print('Password set');
}
int get length => _value.length;
bool get isSet => _value.isNotEmpty;
String get masked => '*' * _value.length;
String get strength {
if (_value.length >= 12) return 'strong';
if (_value.length >= 8) return 'okay';
return 'none';
}
}
void main() {
var p = Password();
print('Set? ${p.isSet}');
p.value = 'abc';
p.value = 'dart2026rocks';
print('Set? ${p.isSet}, length ${p.length}, ${p.masked}, ${p.strength}');
}Output
Set? false
Rejected: "abc" is too short
Password set
Set? true, length 13, *************, strongThere's a setter for value but no getter, so outside code can set a password but never read it
back. Only safe things (length, masked, strength) are exposed. A getter can have a full
{ } body too, like strength.
Common Beginner Mistakes
1. Calling a getter with brackets
print(r.area());Error: 'area' isn't a function or method and can't be invoked.Getters are read like fields: r.area.
2. Assigning to a getter with no setter
r.area = 10;Error: The setter 'area' isn't defined for the type 'Rectangle'.area is calculated, so it can't be set.
3. A getter that returns itself
class Person {
int _age = 0;
int get age => age;
}Unhandled exception:
Stack Overflowage calls the age getter, which calls age, and so on forever. Return the private field:
int get age => _age;.
4. Getters and setters that check nothing: int get x => _x; set x(int v) => _x = v; adds
code but no protection. Use a plain public field unless you need a rule or a calculation.
Practice Questions
- Write a getter
fullNamefor a class withfirstNameandlastName. - How do you read a getter called
total? - Write a setter for
_quantitythat ignores values below 1. - Why doesn't
r.area = 10work for the Rectangle class? - Getter or method:
isEmpty?sendEmail(to)?
Practice Answers
String get fullName => '$firstName $lastName';obj.total, without brackets.
set quantity(int value) {
if (value < 1) return;
_quantity = value;
}areahas a getter but no setter.isEmpty→ getter;sendEmail(to)→ method.
Key Takeaways
Type get name => ...is a getter: read like a field, calculated each time.set name(Type value) { ... }is a setter: runs on assignment and can reject bad values.- Pair them with a private
_fieldthat stores the real value. - No setter = read-only from outside.
- A getter must return the private field, never call itself.