Sub topic 7
Initializing fields: required parameters and initializer lists
Prerequisites
This chapter assumes that you know basic Dart variables, classes, constructors, named parameters, and static types. You should also know that a non-nullable field cannot contain null.
Why initialization matters
Every non-nullable instance field must receive a value before the object can be used. Dart checks this rule at compile time. The check prevents an object from being created with an uninitialized field.
A constructor can initialize fields in three common ways:
- Give a field a declaration-time default.
- Receive a value through a required or optional parameter.
- Compute a value in an initializer list.
A required named parameter must be supplied by the caller. It does not make the value nullable. For example, required this.name requires a non-null String argument and assigns it directly to the name field.
class User {
final String name;
final String? email;
User({
required this.name,
this.email,
});
}
void main() {
final user = User(name: 'Ada');
print(user.name); // Ada
print(user.email ?? 'no email'); // no email
}email is nullable because a user may not have an email address. name is non-nullable, so the constructor requires it.
Initializer lists
An initializer list follows the constructor's parameter list and starts with a colon. It runs before the constructor body. Use it when a field needs a value derived from a parameter or when a final field needs validation.
class Account {
final String owner;
final double balance;
Account({
required String owner,
double initialBalance = 0,
}) : owner = owner.trim(),
balance = _checkBalance(initialBalance) {
if (this.owner.isEmpty) {
throw ArgumentError('owner cannot be empty');
}
}
static double _checkBalance(double value) {
if (value < 0) {
throw ArgumentError('balance cannot be negative');
}
return value;
}
}
void main() {
final account = Account(
owner: ' Ada ',
initialBalance: 100,
);
print(account.owner); // Ada
print(account.balance); // 100.0
}The initializer list trims the owner and validates the balance before the constructor body runs. The constructor body then checks the already-initialized owner field.
The order is important:
- Arguments are evaluated.
- The initializer list runs.
- Instance fields receive their values.
- The constructor body runs.
Choosing between the two forms
Use initializing formal parameters when the parameter maps directly to a field:
class Point {
final double x;
final double y;
Point({
required this.x,
required this.y,
});
}Use an initializer list when the field needs transformation, validation, or a value based on several parameters:
class Temperature {
final double celsius;
final bool isFreezing;
Temperature(double celsius)
: celsius = celsius,
isFreezing = celsius <= 0;
}A constructor body cannot assign a final field after construction has started. It also cannot solve the requirement that a non-nullable field already be initialized before the body runs. Put that work in the initializer list or provide a declaration-time value.
Common errors
- Omitting a
requiredargument causes a compile-time error. - Assigning
nullto a non-nullable field causes a compile-time error. - Calling an instance method from an initializer list can be invalid because the object is not fully initialized. Prefer a top-level function or a static method for validation.
- Putting validation only in the constructor body may allow invalid values to be assigned temporarily. Validate in the initializer list when possible.
Exercise
Why should Account.balance be initialized in the initializer list instead of assigned in the constructor body?
Show answer
The initializer list establishes the value before the constructor body runs, which satisfies the non-nullable final field requirement and allows validation during construction.