Sub topic 2
Fields, Methods, Getters, and Setters
This chapter covers the members that make up the body of a Dart class: fields, methods, getters, and setters. It assumes you know basic Dart syntax (variables, functions, control flow) and null safety (nullable and non-nullable types), and that you have seen objects and methods before. Constructors, privacy, and static members have their own chapters, so they appear here only where needed.
Members of a class
A class body holds members. The four you use most are:
- Fields, which store state.
- Methods, which are functions that run on an instance.
- Getters, which compute a value that is read like a field.
- Setters, which run code when a value is assigned like a field.
Every instance gets its own copy of each instance field. Methods, getters, and setters are shared code that runs against a particular instance, which the body can refer to as this.
Fields
A field is a variable declared inside a class. Its type and modifiers decide how it can be used.
class Account {
final String owner;
double balance = 0;
String? nickname;
late final String id;
Account(this.owner);
}Each declaration here behaves differently:
final String owneris set once, before the constructor body runs, and never changes.double balance = 0is mutable and has an initializer, so it needs no constructor work.String? nicknameis nullable. A nullable field without an initializer starts asnull.late final String idis assigned later, exactly once. Reading it before assignment throws aLateInitializationError.
A non-nullable field must have a value by the time the constructor body starts. Either give it an initializer, set it through an initializing formal such as this.owner, or mark it late. If you do none of these, the analyzer reports an error.
Implicit accessors
Every non-private instance field gives you a getter. Every non-final, non-late-final field also gives you a setter. These accessors are generated for you, so the following two lines use them without any code on your part.
void main() {
final account = Account('Ada');
account.balance = 120.5;
print(account.balance);
}This is why Dart code rarely writes getBalance() and setBalance(). A plain public field already exposes the same interface. If you later need logic around the access, you can replace the field with an explicit getter and setter, and callers do not change.
Methods
A method is a function that belongs to an instance. It can read and write the instance's fields directly, without writing this..
class Counter {
int value = 0;
void increment([int by = 1]) {
value += by;
}
bool isAbove(int limit) => value > limit;
}Use this. only when a parameter or local variable has the same name as a field, or when you want to make the access explicit.
class Box {
int size = 0;
void resize(int size) {
this.size = size;
}
}Methods that return a single expression can use =>. Methods can have positional, optional, and named parameters like any other function.
Operators are methods
Dart lets a class define operators such as +, ==, and [] as methods named with the operator keyword. This is a good way to see that an operator is just a method call.
class Money {
final int cents;
const Money(this.cents);
Money operator +(Money other) => Money(cents + other.cents);
@override
bool operator ==(Object other) =>
other is Money && other.cents == cents;
@override
int get hashCode => cents.hashCode;
}If you override ==, also override hashCode. Two objects that compare equal must return the same hash code, or they will misbehave as Map keys and Set elements.
Getters
A getter is a method with no parameter list, declared with the get keyword. Callers read it with no parentheses, so it looks like a field.
class Rectangle {
final double width;
final double height;
Rectangle(this.width, this.height);
double get area => width * height;
bool get isSquare => width == height;
}area is recomputed on every read. Nothing is stored. This is the main reason to prefer a getter over a field: the value can never go out of date relative to the fields it derives from.
A getter should be cheap and free of side effects. Callers expect rectangle.area to behave like reading a field. If an operation is expensive, does I/O, or changes state, write a method such as computeArea() so the call site shows that work happens.
Setters
A setter is declared with the set keyword and takes exactly one parameter. Callers assign to it with =.
class Thermostat {
double _celsius = 20;
double get celsius => _celsius;
set celsius(double value) {
if (value < -50 || value > 60) {
throw RangeError.range(value.toInt(), -50, 60, 'celsius');
}
_celsius = value;
}
double get fahrenheit => _celsius * 9 / 5 + 32;
set fahrenheit(double value) {
celsius = (value - 32) * 5 / 9;
}
}The leading underscore on _celsius makes it private to the library. The next chapter covers that in detail. Here it matters because it forces every write through the setter, so validation cannot be bypassed from outside the file.
Notice that fahrenheit has both a getter and a setter but no backing field. It is a view of _celsius in other units. Its setter reuses the celsius setter, so the range check applies to both.
void main() {
final t = Thermostat();
t.fahrenheit = 100;
print(t.celsius.toStringAsFixed(1));
t.celsius = 99;
}The first assignment stores about 37.8. The last line throws a RangeError.
Rules for accessor pairs
- A getter and setter with the same name must be declared in the same class, and the getter's return type must match the setter's parameter type.
- A setter has no return type. Its value is the assigned expression, not anything the setter returns.
- If you declare only a getter, the property is read-only. Assigning to it is a compile-time error.
- If you declare only a setter, the property is write-only. This is legal but unusual, so check that a method would not read better.
Choosing a field or an accessor
Start with a plain field. Switch to a getter or setter when you have a reason.
| Situation | Use |
|---|---|
| Simple stored value, no rules | Public field |
| Value must never change after construction | `final` field |
| Value derived from other fields | Getter |
| Writes need validation or side effects | Private field with getter and setter |
| Work is expensive or has side effects | Method |
Edge cases and common errors
Getters and `final` fields are not the same thing
A final field stores one value that is computed once. A getter computes every time. These two classes look alike but differ when the inputs change.
class Snapshot {
final List<int> items;
final int total;
Snapshot(this.items) : total = items.fold(0, (a, b) => a + b);
}
class Live {
final List<int> items;
Live(this.items);
int get total => items.fold(0, (a, b) => a + b);
}
void main() {
final shared = [1, 2];
final snapshot = Snapshot(shared);
final live = Live(shared);
shared.add(10);
print(snapshot.total);
print(live.total);
}This prints 3 and then 13. final stops you reassigning the field, but the list it holds can still be modified. The snapshot captured the total at construction time, and the getter recomputes it.
Promotion does not work on getters
Dart's null-check promotion applies to local variables and to private final fields, but not to public fields or getters. The compiler cannot assume a getter returns the same value twice.
class Profile {
String? bio;
int bioLength() {
if (bio != null) {
return bio!.length;
}
return 0;
}
}The ! is needed because bio is a public mutable field. Copy it into a local variable to avoid the operator:
class Profile {
String? bio;
int bioLength() {
final text = bio;
if (text != null) {
return text.length;
}
return 0;
}
}Setter assignment and compound operators
Compound assignments such as += call the getter and then the setter. With the Thermostat above, t.celsius += 5 reads celsius, adds five, and writes the result through the validating setter.
Infinite recursion
A setter that assigns to its own name calls itself.
class Broken {
int get count => count;
set count(int value) => count = value;
}Both accessors call themselves forever and overflow the stack. Always store the data in a differently named backing field, such as _count.
Late fields and getters
A late field with an initializer runs that initializer lazily, the first time the field is read. This gives you a cached computed value.
class Report {
final List<int> data;
Report(this.data);
late final int total = data.fold(0, (a, b) => a + b);
}Unlike a getter, total is computed once and then stored. Use this only when the data does not change afterward.
How the pieces relate
Exercises
Exercise
A class has final double radius; and the getter double get diameter => radius * 2;. A teammate wants to change diameter to a final field computed in the constructor. Name one benefit and one risk of this change.
Show answer
The benefit is that the value is computed once instead of on every read, which helps if the computation is costly. The risk is that the stored value can go stale if anything it was derived from can change. Here radius is final, so the risk is small, but with mutable inputs the field would drift out of date while the getter would not.
Exercise
What happens when you run this code, and how do you fix it? class Score { int get value => value; set value(int v) => value = v; }
Show answer
Both the getter and the setter call themselves, so any read or write recurses until the stack overflows. Fix it by adding a private backing field, int _value = 0;, then writing int get value => _value; and set value(int v) => _value = v;.
Exercise
Why does if (profile.bio != null) { return profile.bio.length; } fail to compile when bio is a public String? field, and what is a clean fix that avoids !?
Show answer
Public fields and getters are not promoted, because the compiler cannot guarantee that two reads return the same value. Copy the value into a local variable with final text = profile.bio;, test text != null, and use text.length, since local variables are promoted.