Sub topic 2
Fields, Methods, Getters, and Setters in Dart
This chapter assumes basic Dart syntax, null safety, variables, functions, and control flow. It also assumes that you know an object stores data and exposes operations.
A class groups related data and behavior. A field stores data on each object. A method is a function defined inside a class. A getter reads a value through property syntax. A setter changes a value through property syntax while allowing validation or other logic.
Fields store object state
An instance field belongs to one object. Each object has its own value unless the field is declared static, which is covered later.
Use final when a field should be assigned once. A final field can still refer to a mutable object, but the field itself cannot refer to a different object.
Methods provide behavior
A method can read fields, change mutable fields, return a value, or perform an action. Use a method when the operation represents an action or needs arguments.
The following class uses all four member types:
class Playlist {
final String name;
final List<String> songs;
int _volume = 50;
Playlist(this.name, this.songs);
int get volume => _volume;
set volume(int value) {
if (value < 0 || value > 100) {
throw ArgumentError('Volume must be between 0 and 100');
}
_volume = value;
}
int get songCount => songs.length;
void addSong(String song) {
songs.add(song);
}
String describe() {
return '$name has $songCount song(s) at volume $volume';
}
}
void main() {
final playlist = Playlist('Road Trip', ['Drive']);
playlist.addSong('Sunrise');
playlist.volume = 75;
print(playlist.describe());
}The name and songs fields hold the playlist's state. The addSong and describe methods perform actions. The songCount getter computes a value from existing state, so callers use playlist.songCount instead of playlist.songCount().
| Member | Main purpose | Calling syntax |
|---|---|---|
| Field | Store state | `playlist.name` |
| Method | Perform an operation | `playlist.addSong('Sunrise')` |
| Getter | Read or compute a property | `playlist.songCount` |
| Setter | Validate and assign a property | `playlist.volume = 75` |
Getters and setters
A getter is declared with get. It looks like a field to callers, but Dart runs its body when the value is read. Getters are useful for calculated values, read-only views, and hiding how data is stored.
A setter is declared with set and takes exactly one parameter. It also looks like a field assignment. Use one when assigning a value requires validation, conversion, or another side effect.
A getter does not have to have a matching setter. A read-only computed property, such as songCount, is often safer than exposing a value that callers could change directly.
Common errors
- Calling a getter with parentheses: write
playlist.songCount, notplaylist.songCount(). - Forgetting validation in a setter when invalid state would break later methods.
- Exposing mutable fields when callers should use controlled methods.
- Declaring a field nullable without deciding how code handles
null.
Exercise
Why is songCount a getter instead of a stored field?
Show answer
It is derived from the current length of songs, so calculating it avoids duplicated state that could become inconsistent.