Sub topic 8
Redirecting Constructors
This chapter assumes you can write a basic Dart class, know generative and named constructors, and understand final fields and initializer lists. It covers redirecting generative constructors, redirecting factory constructors, and the errors you are most likely to hit with each.
What a redirecting constructor does
A redirecting constructor does no work of its own. It forwards to another constructor in the same class (or, for factories, to a constructor of another class) and lets that constructor do the initialization. Use one when several constructors differ only in which arguments they supply, and you want the real initialization written once.
Dart has two forms:
- A redirecting generative constructor forwards to another generative constructor of the same class with
this(...). - A redirecting factory constructor forwards to a constructor of the same class or of a subtype with
= ClassName(...).
Redirecting generative constructors
A redirecting generative constructor has no body. After the colon it names another constructor of the same class by writing this or this.name:
class Point {
final double x;
final double y;
const Point(this.x, this.y);
// Redirects to the main constructor.
const Point.onXAxis(double x) : this(x, 0);
// Redirects to another named constructor.
const Point.origin() : this.onXAxis(0);
@override
String toString() => 'Point($x, $y)';
}
void main() {
print(Point.onXAxis(3));
print(Point.origin());
}This prints Point(3.0, 0.0) and then Point(0.0, 0.0). The integer literals convert to double because the parameters have type double.
Point.origin() redirects to Point.onXAxis, which redirects to Point. Redirects can chain. Only the final constructor in the chain initializes the fields.
The rules
A redirecting generative constructor is restricted in three ways:
- It has no body. The redirect after the colon is the whole implementation. A
{ ... }body is an error. - It cannot have other initializers. You can't combine
this(...)with a field assignment or asuper(...)call in the same initializer list. The target constructor owns all of that. - It cannot use initializing formals. A parameter such as
this.xis an error, because the redirecting constructor doesn't initialize fields itself.
class Broken {
final int a;
final int b;
Broken(this.a, this.b);
// Error: a redirecting constructor can't also initialize a field.
Broken.one(int a) : b = 1, this(a, 1);
}Dart reports an error here. Move the value computation into the redirect's arguments instead: Broken.one(int a) : this(a, 1);.
Computing arguments in the redirect
The arguments to this(...) are ordinary expressions. They can use the redirecting constructor's parameters, static members, top-level functions, and constants. They cannot use this, because the object is not initialized yet.
class Temperature {
final double celsius;
const Temperature(this.celsius);
Temperature.fromFahrenheit(double f) : this((f - 32) * 5 / 9);
Temperature.freezing() : this(0);
}This is the main benefit of redirection. Temperature.fromFahrenheit converts the value and passes it on. The final field is still assigned in exactly one place.
How initialization runs
When you call a redirecting constructor, Dart evaluates the redirect's arguments first, then runs the target constructor. The target's initializer list and its superclass constructor run as usual. The target's body runs last. The redirecting constructor adds nothing after that.
Redirecting factory constructors
A factory constructor can also redirect. The syntax is an = followed by the target constructor, with no body:
abstract interface class Shape {
double get area;
// Redirecting factory constructors.
const factory Shape.square(double side) = Square;
const factory Shape.unit() = _UnitSquare;
}
class Square implements Shape {
final double side;
const Square(this.side);
@override
double get area => side * side;
}
class _UnitSquare extends Square {
const _UnitSquare() : super(1);
}
void main() {
final Shape s = Shape.square(4);
print(s.area);
print(Shape.unit().area);
}This prints 16.0 and 1.0. The factory Shape.square has no body. The = Square tells Dart to build a Square with the same arguments. The target must produce a subtype of the declaring class, and its parameters must be compatible with the factory's.
This is how an interface or abstract class exposes concrete instances without the caller knowing the implementing class. The caller only sees Shape.
Differences from a redirecting generative constructor
| Feature | Redirecting generative | Redirecting factory |
|---|---|---|
| Syntax | `Name.x() : this(...)` | `factory Name.x() = Target;` |
| Target | Same class only | Same class or a subtype |
| Arguments | You write them in `this(...)` | Passed through unchanged |
| Can be `const` | Yes, if the target is `const` | Yes, if the target is `const` |
| Can compute arguments | Yes | No |
| Can be used on an abstract class | No, abstract classes can't be instantiated, though subclasses may call them | Yes |
The key limit of the factory form is that arguments pass straight through. If you need to transform the arguments, write a normal factory constructor with a body that calls the target instead.
Generic targets
A redirecting factory can name type arguments for its target. This matters when the class is generic:
abstract class Box<T> {
factory Box(T value) = _FullBox<T>;
factory Box.empty() = _EmptyBox<T>;
bool get isEmpty;
}
class _FullBox<T> implements Box<T> {
final T value;
_FullBox(this.value);
@override
bool get isEmpty => false;
}
class _EmptyBox<T> implements Box<T> {
_EmptyBox();
@override
bool get isEmpty => true;
}
void main() {
print(Box(3).isEmpty);
print(Box<String>.empty().isEmpty);
}The output is false and then true. Each target must be written with its type argument, as in _FullBox<T>, so that the types line up.
Redirecting versus a factory with a body
Both forms let a constructor hand back an instance made elsewhere. Pick by what you need:
- Use a redirecting factory when the target is fixed, the arguments pass through unchanged, and you want the redirect to be
const-capable. - Use a factory with a body when you need to compute arguments, choose between targets, cache instances, or return
null-free fallbacks.
A redirecting factory is also the most direct way to write the pattern used by code generators such as freezed, where the public factory points at a generated implementation class.
Common errors
- Adding a body or field initializer. A redirecting generative constructor must be just
: this(...). Move extra logic into the target or into the argument expressions. - Using
this.xparameters. Initializing formals are not allowed in a redirecting constructor. Use a plain parameter and pass it on. - Redirect cycles.
A.one() : this.two();andA.two() : this.one();form a loop. Dart reports a compile-time error for a redirection cycle. - Non-const redirect inside a const constructor. A
constconstructor can only redirect to anotherconstconstructor. If the target isn'tconst, the redirect can't be either. - Target not a subtype. A redirecting factory whose target class doesn't implement the declaring class is an error.
- Mismatched parameters. For a redirecting factory, the target's parameters must accept the factory's. A factory taking
intcan't redirect to a constructor that requiresString.
Practice
Exercise
This class does not compile. Explain why and fix it so Rect.square(5) creates a rectangle with width 5 and height 5.
class Rect {
final double width;
final double height;
Rect(this.width, this.height);
Rect.square(this.width) : this(width, width);
}
Show answer
A redirecting generative constructor can't use an initializing formal such as this.width, because the target constructor does the field initialization. Change the parameter to a plain one: Rect.square(double side) : this(side, side);. The redirect then passes the value to Rect, which assigns both final fields.
Exercise
Why can't a redirecting factory constructor such as factory Shape.square(double side) = Square; convert its argument, for example by doubling it? What do you write instead?
Show answer
A redirecting factory has no body and no argument expressions. It passes its arguments unchanged to the target constructor. To change the argument, write a factory with a body, such as factory Shape.doubled(double side) { return Square(side * 2); }, or redirect a generative constructor with this(...) when the target is in the same class.