Sub topic 1
Classes and objects
Prerequisites
This chapter assumes you know basic Dart syntax, including variables, functions, and control flow. You should also understand nullable and non-nullable types, and have a general idea of what an object is.
Classes and objects
A class is a blueprint. An object is an instance created from that blueprint. Each object holds its own values, and its class defines what those values are and what the object can do.
Fields, methods, getters, and setters
Fields store state. Methods perform actions. A getter exposes a computed or stored value as if it were a field. A setter runs code when a value is assigned, which lets you validate input.
class Account {
final String owner;
double _balance = 0;
static int accountCount = 0;
Account(this.owner) {
accountCount++;
}
double get balance => _balance;
set balance(double value) {
if (value < 0) {
throw ArgumentError('Balance cannot be negative');
}
_balance = value;
}
void deposit(double amount) {
_balance += amount;
}
}
void main() {
final alice = Account('Alice');
alice.deposit(50);
print('${alice.owner}: ${alice.balance}');
print('Accounts: ${Account.accountCount}');
}Running this prints Alice: 50.0 and Accounts: 1.
Privacy with a leading underscore
A name that starts with _ is library-private. Code outside the library cannot access it. In Dart, the library is usually a single file, so _balance is hidden from other files but visible inside its own file. Privacy is per library, not per class.
Static fields and methods
A static member belongs to the class itself, not to any one object. Account.accountCount counts every account created, while each object still has its own owner and balance.
Generative constructors and initializing formals
A generative constructor creates a new instance. The initializing formal this.owner assigns the parameter directly to the field. Use final for fields that should not change after construction, and assign them through the constructor, an initializer list, or an initializing formal.
Note that Account(this.owner) runs its body after the field is set, so the accountCount++ line runs for every new object.
Exercise
In the example above, what happens if you run alice.balance = -5;?
Show answer
The setter runs, the check value < 0 is true, and it throws an ArgumentError with the message "Balance cannot be negative". The stored balance does not change.