Sub topic 7
Named Constructors
A Dart class can have more than one way to be created. Named constructors give each way its own name, so call sites say what they mean. This chapter assumes you know generative constructors with initializing formals (this.x), final fields, and null safety. It also assumes you have seen an initializer list. The next chapters cover redirecting and factory constructors, which build on this one.
Why a class needs more than one constructor
Dart has no constructor overloading. A class can declare only one constructor with the same name as the class, the unnamed constructor. If a Point is built from two numbers, you can't also declare a second Point(Map json).
Named constructors solve this. The syntax is ClassName.name, and the name is part of the constructor's identity:
import 'dart:math';
class Point {
final double x;
final double y;
const Point(this.x, this.y);
const Point.origin()
: x = 0,
y = 0;
Point.polar(double radius, double angle)
: x = radius * cos(angle),
y = radius * sin(angle);
Point.fromJson(Map<String, Object?> json)
: x = (json['x'] as num).toDouble(),
y = (json['y'] as num).toDouble();
@override
String toString() => 'Point($x, $y)';
}
void main() {
print(const Point(3, 4));
print(const Point.origin());
print(Point.polar(2, pi / 2));
print(Point.fromJson({'x': 1, 'y': 2.5}));
}Each constructor has a different parameter list and a different input format. The result is always a Point. You call a named constructor like any other: Point.origin(). With a const constructor you can add const in front, as main does above.
How a named constructor initializes fields
A named constructor does the same job as an unnamed one. It must give every non-nullable final field a value before its body runs. There are two ways to do that:
- Initializing formals.
this.xin the parameter list assigns the argument straight to the field. - The initializer list. Assignments after the colon run before the constructor body.
Point.polar needs the initializer list because the fields are computed from the arguments. It can't use this.x. The initializer list can use the parameters, but it can't use this. For example, y = x * 2 would be an error in an initializer list, because x there would refer to the field before it exists.
You can also validate inputs with assert in the same list. Asserts run only in debug mode:
class Percentage {
final double value;
Percentage.fromFraction(double fraction)
: assert(fraction >= 0 && fraction <= 1),
value = fraction * 100;
Percentage.fromPercent(this.value)
: assert(value >= 0 && value <= 100);
}If you need a statement-style computation that doesn't fit in an expression, do the work in a static helper and call it from the list. Or consider a factory constructor, which is covered later.
Order of execution
Creating an object with a named constructor follows the same steps as any generative constructor.
The initializer list runs first, left to right. Then the superclass constructor runs. Then the body runs, and only the body can use this. If you want the superclass constructor call written explicitly, put it last in the initializer list.
The default constructor disappears
If a class declares no constructor at all, Dart supplies an unnamed constructor with no arguments. Once you declare any constructor, named or not, that implicit one is gone. This catches people out:
class Tag {
final String label;
Tag.fromText(String text) : label = text.trim();
}
void main() {
// Tag('a') is a compile-time error: Tag has no unnamed constructor.
print(Tag.fromText(' news ').label);
}Here Tag can only be created through fromText. That is sometimes exactly what you want, but remember it when you add a named constructor to an existing class. Any code that called the implicit constructor stops compiling.
Private named constructors
A name that starts with an underscore is private to its library, which is usually a file. A private named constructor, written ClassName._, blocks outside code from creating instances directly. Code in the same library can still call it. The usual pattern is to expose controlled entry points, such as static methods:
class Config {
final Map<String, String> values;
Config._(this.values);
static Config parse(String text) {
final values = <String, String>{};
for (final pair in text.split(';')) {
final parts = pair.split('=');
if (parts.length == 2) {
values[parts[0].trim()] = parts[1].trim();
}
}
return Config._(values);
}
}
void main() {
final config = Config.parse('mode = dark; size = 12');
print(config.values['mode']);
}The same idea appears again with factory constructors, where a private named constructor does the real construction and the public factory decides whether to call it.
Named constructor or static method?
A static method such as Config.parse can do things a constructor can't: it can be async, return null, or return a subtype. A named constructor can't be async, and it always produces a new instance of that exact class. Use this table to decide:
| Need | Use |
|---|---|
| Create an instance from different inputs, with `final` fields set directly | Named constructor |
| Create a compile-time constant | `const` named constructor |
| Reuse an instance, or return a subtype | Factory constructor |
| Return a `Future`, or `null` on failure | Static method |
Named constructors read well at the call site and work with tear-offs, as in list.map(Point.fromJson). Dart 3 also allows .new for the unnamed constructor, as in Point.new.
Named constructors are not inherited
A subclass doesn't get its superclass's named constructors. The subclass has to declare its own, and each one must decide which superclass constructor to call:
class Point {
final double x;
final double y;
const Point(this.x, this.y);
const Point.origin()
: x = 0,
y = 0;
}
class Point3D extends Point {
final double z;
Point3D(super.x, super.y, this.z);
Point3D.origin()
: z = 0,
super.origin();
}Point3D.origin() sets z itself and calls the superclass's named constructor with super.origin(). Without that declaration, Point3D.origin() would not compile, even though Point has an origin constructor.
If the subclass constructor does not call super explicitly, Dart implicitly calls the superclass's unnamed, zero-argument constructor. If that doesn't exist, you get a compile-time error. This is the other common surprise after adding a named constructor to a superclass.
Common errors
- Using
thisin the initializer list. Move the work to the body, or use only the parameters. - Forgetting a
finalfield. Every non-nullablefinalfield without a default needs a value from each generative constructor, named ones included. - Duplicate names. Two constructors can't share a name.
Point.originandPoint.originconflict even with different parameters. - Name clashes with members. A named constructor and a static member can't have the same name.
Point.origin()andstatic Point originwould conflict. - Assuming
constis automatic. A constructor must be declaredconst, and all its fields must befinal, before callers can writeconst Point.origin().
Exercise
Add a named constructor Point.fromList(List<double> values) to the Point class from this chapter. It should take the first two items as x and y, and in debug mode it should fail if the list has fewer than two items. What goes after the colon?
Show answer
Point.fromList(List<double> values) : assert(values.length >= 2), x = values[0], y = values[1]; The assert runs first. The two assignments initialize the final fields from the parameter. The initializer list can use values but not this.
Exercise
A class Base declares only Base.named(). A subclass Child extends Base declares only Child();. Why does this fail to compile, and how do you fix it?
Show answer
Without an explicit call, Child's constructor implicitly calls Base's unnamed zero-argument constructor, which doesn't exist because Base declared a constructor. The fix is to call the one that exists: Child() : super.named();.