Sub topic 7
Named constructors in Dart
Assume you know Dart variables, functions, null safety, and basic classes. A named constructor is a constructor with an identifier after the class name. It gives a class more than one clear way to create an object.
An unnamed constructor is called with only the class name:
final origin = Point(0, 0);A named constructor is called with a dot:
final origin = Point.origin();
final point = Point.fromJson({'x': 3, 'y': 4});The name should describe where the data comes from or what the object represents.
Defining named constructors
Dart constructors do not have a return type. A named constructor uses this form:
ClassName.constructorName(arguments)Here is a complete example:
class Point {
final double x;
final double y;
const Point(this.x, this.y);
const Point.origin()
: x = 0,
y = 0;
Point.fromJson(Map<String, Object?> json)
: x = (json['x'] as num).toDouble(),
y = (json['y'] as num).toDouble();
double distanceSquaredTo(Point other) {
final dx = x - other.x;
final dy = y - other.y;
return dx * dx + dy * dy;
}
}
void main() {
const origin = Point.origin();
final point = Point.fromJson({'x': 3, 'y': 4});
print(origin.x); // 0.0
print(point.distanceSquaredTo(origin)); // 25.0
}Point.origin creates a point with fixed coordinates. Point.fromJson creates a point from a map, such as decoded data from a file or an API.
The initializer list runs before the constructor body. It is useful for assigning final fields because those fields must receive a value during construction.
Choosing constructor names
Use a name that makes the creation rule obvious.
| Constructor | Appropriate meaning |
|---|---|
| `User.guest()` | Creates a user with guest settings |
| `DateTime.now()` | Uses the current time |
| `Color.fromHex(String value)` | Parses a hexadecimal value |
| `Point.origin()` | Creates a point at a known location |
A class can have an unnamed constructor and several named constructors. Each constructor must have a different parameter signature or name. Named constructors are especially useful when positional arguments alone would not explain the object's source.
Redirecting named constructors
A redirecting constructor sends construction to another constructor in the same class. It has no initializer list or body.
class User {
final String name;
final bool isGuest;
User(this.name, this.isGuest);
User.guest() : this('Guest', true);
}
void main() {
final user = User.guest();
print('${user.name}: ${user.isGuest}');
}User.guest() reuses the main constructor, so the initialization logic has one source of truth.
Exercise
Which constructor call creates a point at the origin: Point(0, 0) or Point.origin()?
Show answer
Both can create the same values, but Point.origin() communicates the meaning more clearly and centralizes that construction rule.