Sub topic 8
Classes and constructors
This chapter assumes you know the basics of variables, final and const, null safety, and functions with named parameters. It also assumes you know what classes and objects are from another language. Here you will see how Dart declares classes and which constructor kinds it offers. You will also see how an object is built step by step, and which errors come up most often.
A minimal class
A class declares fields (data) and methods (behavior). You create an instance by calling the class name like a function. Dart has no new keyword in modern code.
class Account {
final String owner;
double _balance;
Account(this.owner, {double balance = 0})
: _balance = balance,
assert(balance >= 0);
double get balance => _balance;
void deposit(double amount) {
if (amount <= 0) throw ArgumentError.value(amount, 'amount', 'must be positive');
_balance += amount;
}
}
void main() {
final acct = Account('Ada', balance: 10);
acct.deposit(5);
print('${acct.owner}: ${acct.balance}');
}This one small class already shows several features:
this.owneris an initializing formal. It copies the argument straight into the field, so you don't writethis.owner = owneryourself.- The part after the colon is the initializer list. It runs before the constructor body and can set fields and check assertions.
- A name starting with
_is private to its library, which is normally the file. It is not private to the class. Another class in the same file can read_balance. get balanceis a getter. Callers writeacct.balance, with no parentheses.
Generative constructors
A generative constructor creates a new instance of its own class. Without any constructor, Dart gives the class a default no-argument one. If you declare any constructor, the default disappears.
Every non-nullable field needs a value before the constructor body starts. A field can get its value in three ways:
- A default in its declaration:
int count = 0; - An initializing formal:
Account(this.owner) - An initializer list entry:
: _balance = balance
If a field has none of these, the analyzer reports an error. The exception is late, which promises you will assign the field before it is read.
class Report {
final List<int> data;
late final int total = data.fold(0, (a, b) => a + b);
Report(this.data);
}A late field with an initializer runs it lazily, on first read. That is why the initializer can use data. Ordinary field initializers and the initializer list can't use this.
Construction order
Dart builds an object in a fixed order. The initializer list runs first, then the superclass constructor, then the subclass body.
The next program prints a line at each stage so you can see the order:
int _trace(String message, int value) {
print(message);
return value;
}
class Vehicle {
final String id;
Vehicle(this.id) {
print('Vehicle body $id');
}
}
class Car extends Vehicle {
final int doors;
Car(String id, int doors)
: doors = _trace('Car initializer', doors),
super(id) {
print('Car body $doors');
}
}
void main() {
Car('c1', 4);
}The output is Car initializer, then Vehicle body c1, then Car body 4. The super(...) call must be last in the initializer list.
Named and redirecting constructors
A class has only one unnamed constructor. For other ways to build an object, use named constructors of the form ClassName.name. A redirecting constructor has no body and forwards to another constructor with : this(...).
class Point {
final double x;
final double y;
const Point(this.x, this.y);
const Point.origin() : this(0, 0);
Point.fromList(List<double> xs) : this(xs[0], xs[1]);
@override
String toString() => 'Point($x, $y)';
}
void main() {
print(const Point.origin());
print(Point.fromList([2, 3]));
}Point.fromList can't be const, because indexing a list isn't a compile-time operation.
Const constructors
A const constructor lets the compiler build the object at compile time. Two requirements apply:
- Every field must be
final. - The initializer list may use only compile-time constants.
Dart canonicalizes const instances. Two const expressions with equal arguments give the same object in memory.
void main() {
const a = Point(1, 2);
const b = Point(1, 2);
final c = Point(1, 2); // runtime instance, not canonical
print(identical(a, b)); // true
print(identical(a, c)); // false
}This is why Flutter code writes const Text('Hi') in so many places. Flutter reuses the same widget object and can skip rebuilding it. Calling a const constructor without the const keyword, in a context that doesn't require it, creates an ordinary runtime object.
Factory constructors
A factory constructor is not required to create a new instance. It can return a cached object, or an instance of a subtype. It has no this, and it can't use an initializer list or initializing formals.
class Logger {
static final Map<String, Logger> _cache = {};
final String name;
Logger._internal(this.name);
factory Logger(String name) =>
_cache.putIfAbsent(name, () => Logger._internal(name));
factory Logger.fromConfig(Map<String, String> config) =>
Logger(config['name'] ?? 'default');
void log(String message) => print('[$name] $message');
}
void main() {
final a = Logger('app');
final b = Logger('app');
print(identical(a, b)); // true
a.log('started');
}Logger._internal is a private named constructor. Code outside the file can't call it, so the factory controls every instance.
Getters, setters, and computed properties
A getter or setter looks like a field to callers. Use one when a value is derived from other state or needs validation. Don't use one as a ritual wrapper around a plain field, because Dart fields already behave like properties.
class Square {
double _side;
Square(this._side);
double get side => _side;
set side(double value) {
if (value < 0) throw ArgumentError('side must be >= 0');
_side = value;
}
double get area => _side * _side;
}A final field has only a getter. A non-final field gets both automatically, and you can replace it with an explicit pair later without changing any caller.
Choosing a constructor kind
| Need | Use |
|---|---|
| Plain construction | Generative constructor with initializing formals |
| Several ways to build the same class | Named constructors |
| Reuse another constructor's logic | Redirecting constructor (`: this(...)`) |
| Immutable, shareable values | `const` constructor, all fields `final` |
| Caching, or returning a subtype | `factory` constructor |
| Value computed on first use | `late` field with an initializer |
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| Non-nullable field "must be initialized" | No default, initializing formal, or initializer list entry | Initialize it, make it nullable, or mark it `late` |
| `this` is not available in an initializer | Initializers run before the object exists | Move the logic into the body, or make the field `late` |
| "Can't define a const constructor for a class with non-final fields" | A mutable field in a `const` class | Make every field `final` |
| `LateInitializationError` | A `late` field was read before assignment | Assign it earlier, or give it an initializer |
| Named parameter `{this._count}` rejected | Named parameters can't start with an underscore | Use `{int count = 0}` with `: _count = count` |
| A subclass constructor can't find a superclass constructor | The superclass has no unnamed no-argument constructor | Call one explicitly with `super(...)` |
Exercises
Exercise
A class has final int a; final int b; and the constructor Pair(int a) : b = a * 2, a = a;. Is this legal, and what does Pair(3) hold? Then explain why Pair(int a) : b = this.a * 2, a = a; fails.
Show answer
The first version is legal. Initializer list entries can appear in any order, so Pair(3) has a = 3 and b = 6. The second version fails because the initializer list can't refer to this. The object doesn't exist yet, so this.a is not available. Use the parameter a instead.
Exercise
Write a class Temperature with a final double celsius field, a const unnamed constructor, a named constructor Temperature.fromFahrenheit(double f) that reuses it, and a getter fahrenheit. Why can the named constructor not be const if it does arithmetic on a parameter?
Show answer
class Temperature {
final double celsius;
const Temperature(this.celsius);
Temperature.fromFahrenheit(double f) : this((f - 32) 5 / 9);
double get fahrenheit => celsius 9 / 5 + 32;
}
A const constructor's initializers must be compile-time constants. The value of f is only known when the program runs, so the redirect can't be evaluated by the compiler. It would be allowed only if every call site passed a constant, and even then the constructor itself would have to be declared const with a constant-only body.