Sub topic 10
Factory Constructors in Dart
Factory constructors control how an object is obtained. Unlike a generative constructor, a factory constructor does not always create a new instance. It can return a cached object, a subtype, or an object created by another constructor.
This chapter assumes basic Dart syntax, null safety, and familiarity with classes and methods.
How a factory constructor works
A factory constructor uses the factory keyword. It cannot access this before returning an object because it may return an object that already exists. The constructor must return an instance of its class or one of its subclasses.
A common use is caching. The class below returns one Logger instance for each 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 first = Logger('network');
final second = Logger('network');
final other = Logger('database');
print(identical(first, second)); // true
print(identical(first, other)); // false
first.log('Request started');
}_internal is a private generative constructor. The factory uses it when the cache does not contain the requested name. The leading underscore makes the constructor library-private, so code in other libraries cannot call it directly.
The putIfAbsent method returns the existing value when the key is present. Otherwise, it calls the function and stores the new value.
Factory and generative constructors
A generative constructor initializes a new object directly. A factory constructor decides which object to return.
| Constructor kind | Always creates a new instance? | Can return a cached instance? | Can return a subtype? |
|---|---|---|---|
| Generative | Yes | No | No |
| Factory | No | Yes | Yes |
Use a factory when object creation needs a decision. Examples include caching, returning different implementations, validating or normalizing input, and creating instances from a data format.
A factory can also redirect to another constructor:
abstract class PaymentMethod {
factory PaymentMethod.fromJson(Map<String, Object?> json) {
switch (json['type']) {
case 'card':
return CardPayment(json['number'] as String);
case 'cash':
return CashPayment();
default:
throw FormatException('Unknown payment type');
}
}
}
class CardPayment implements PaymentMethod {
final String number;
CardPayment(this.number);
}
class CashPayment implements PaymentMethod {}The factory hides the concrete class selected by the input. Callers depend on PaymentMethod, while the factory chooses CardPayment or CashPayment.
Common errors and trade-offs
Do not use a factory only because it looks shorter. A generative constructor is simpler when every call should create an independent object.
Caching can reduce allocations, but it also keeps objects alive through the cache. If the cache grows without limits, memory use can grow too. Mutable cached objects can also create surprising shared state.
Avoid returning null from a factory. If construction can fail, throw an exception or use a separate result type such as Result or Nullable logic.
Exercise
Why can two calls to a factory constructor return the same object, while two calls to a generative constructor normally cannot?
Show answer
A factory constructor controls which instance it returns and may return an existing cached instance. A generative constructor allocates and initializes a new instance for each call.