Sub topic 10
Factory constructors
This chapter assumes you know generative constructors, named constructors, and private members (names that start with an underscore). It also assumes you know basic null safety. Here you will learn what a factory constructor is, when to use one, and which rules limit it.
What a factory constructor does
A generative constructor always creates a new instance of its own class. It allocates the object, runs the initializer list, and returns the object, and you can't change that. A factory constructor is different. It is a function that must return an instance of the class's type, but it decides how to get that instance. It can:
- return an object that already exists, for example from a cache
- return an instance of a subclass or of another class that implements the type
- run validation or parsing logic before it picks what to build
- return a different object each time, depending on its arguments
You write one by putting factory before the constructor name and giving it a body that returns a value.
Returning a cached instance
The Logger class below keeps one instance per name.
class Logger {
final String name;
static final Map<String, Logger> _cache = {};
factory Logger(String name) {
return _cache.putIfAbsent(name, () => Logger._internal(name));
}
Logger._internal(this.name);
void log(String message) => print('[$name] $message');
}
void main() {
final a = Logger('app');
final b = Logger('app');
final c = Logger('db');
a.log('started');
print(identical(a, b)); // true
print(identical(a, c)); // false
}There are two constructors here. Logger._internal is a private generative constructor, and only code in the same library can call it. The public Logger factory is the only way outside code gets an instance. It checks the static _cache map first, and putIfAbsent calls the closure only when the name is missing.
Making the generative constructor private is the usual pairing. If a public generative constructor existed too, callers could bypass the cache.
Why the keyword matters: no `this`
A factory constructor runs before any object exists, so it has no this. That leads to several rules:
- It can't use initializing formals such as
this.name. You have to name each parameter normally. - It can't have an initializer list.
- It can't read instance fields or call instance methods.
- It can read and write static members and call other constructors.
The usual pattern is to compute what you need as local variables. Then you call a generative constructor, or return an object you already have.
Returning a subtype
A factory can return an instance of any type that satisfies the class's type. This lets one abstract type hide several concrete implementations.
abstract class Shape {
double get area;
factory Shape.fromJson(Map<String, Object?> json) {
return switch (json['type']) {
'circle' => _Circle((json['radius'] as num).toDouble()),
'square' => _Square((json['side'] as num).toDouble()),
_ => throw FormatException('Unknown shape type', json['type']),
};
}
}
class _Circle implements Shape {
final double radius;
_Circle(this.radius);
@override
double get area => 3.14159 * radius * radius;
}
class _Square implements Shape {
final double side;
_Square(this.side);
@override
double get area => side * side;
}
void main() {
final shapes = [
Shape.fromJson({'type': 'circle', 'radius': 2}),
Shape.fromJson({'type': 'square', 'side': 3}),
];
for (final s in shapes) {
print(s.area);
}
}Callers see only Shape. They never learn that _Circle and _Square exist, because both names are private to the library. You can add a third shape later without changing any calling code.
The factory also reports bad input by throwing. A factory can't return null, because its return type is the non-nullable class type. If "no valid object" is a normal outcome, a static method with a nullable return type fits better.
Redirecting factory constructors
When a factory only forwards to another constructor, you can skip the body and use = followed by the target constructor.
abstract class Point3 {
double get x;
factory Point3(double x) = _Point3Impl;
}
class _Point3Impl implements Point3 {
@override
final double x;
_Point3Impl(this.x);
}
void main() {
print(Point3(4).x); // 4.0
}The parameters of the target must be compatible with the factory's parameters. This is not the same as a redirecting generative constructor, which forwards with : this(...) inside the same class. A redirecting factory can point at a constructor of a different class, as long as that class is a subtype.
A const factory must be a redirecting factory. It has to point at a constant constructor, because a factory with a body can't run at compile time.
Singletons
A factory can also return one shared instance for every call. The cache in Logger is a keyed version of the same idea.
class AppSettings {
AppSettings._();
static final AppSettings instance = AppSettings._();
factory AppSettings() => instance;
String theme = 'light';
}
void main() {
AppSettings().theme = 'dark';
print(AppSettings().theme); // dark
print(identical(AppSettings(), AppSettings.instance)); // true
}static final fields are initialized lazily on first access, so the object is created the first time something asks for it.
Factory or static method?
A static method can do most of what a factory does. The difference is how callers use it.
| Need | Factory constructor | Static method |
|---|---|---|
| Call looks like `Type(...)` or `Type.name(...)` | Yes | No, it looks like `Type.create(...)` |
| Can be a tear-off like `Type.new` | Yes | Only as a method tear-off |
| Can return `null` or `Future<T>` | No | Yes |
| Can be `const` | Only as a redirect | No |
| Can be `async` | No | Yes |
Choose a factory when the result is a real instance of the class and the call should read like construction. Choose a static method when the result may be absent, may arrive later, or needs a verb-style name.
Common mistakes
- Writing
factory Logger(this.name). Factories have nothis, so use a plain parameter. - Leaving a public generative constructor next to the cache. Callers can then create uncached duplicates.
- Forgetting to return a value on every path. A factory body must return an object or throw.
- Expecting
super(...)in a subclass to reach a factory. It calls a generative constructor only. - Storing mutable state in a singleton and then being surprised by shared changes. In
AppSettings, every caller sees the sametheme.
Exercise
The following code does not compile. What is wrong, and how do you fix it? class Token { final String value; factory Token(this.value) { return Token.(value); } Token.(this.value); }
Show answer
A factory constructor has no this and can't use initializing formals, so factory Token(this.value) is invalid. Declare a plain parameter instead: factory Token(String value) { return Token._(value); }. The private generative constructor Token._(this.value) is fine as written.
Exercise
Add a factory constructor Logger.fromEnvironment(Map<String, String> env) to the Logger class. It should return Logger(env['LOGGER_NAME'] ?? 'default'). Can you write it as a one-line expression body? Does it return a cached instance?
Show answer
Yes. Write factory Logger.fromEnvironment(Map<String, String> env) => Logger(env['LOGGER_NAME'] ?? 'default');. It delegates to the unnamed factory, so it returns a cached instance. Two calls with the same name give identical objects.
Exercise
Why must a const factory be a redirecting factory?
Show answer
Constant expressions are evaluated at compile time, and a factory with a body runs arbitrary code that the compiler can't evaluate. A redirecting factory only forwards to a constant constructor, so the compiler can build the constant object directly.