Classes, Enums, Extensions
Factory Constructors
Choosing What to Return
A factory constructor does not always build a fresh instance. It can pick an instance based on input, return a cached value, or fall back to a default. A library-private Color._(...) generative constructor builds the values the factory hands out.
Program
Play the program to ask for two colors and watch the factory dispatch to a known case and a fallback.
factory_constructors.dart
class Color {
final String name;
final int code;
Color._(this.name, this.code);
factory Color.named(String name) {
switch (name) {
case 'red':
return Color._('red', 1);
case 'green':
return Color._('green', 2);
default:
return Color._('unknown', 0);
}
}
}
void main() {
var a = Color.named('red');
var b = Color.named('purple');
print('${a.name}=${a.code} ${b.name}=${b.code}');
}
factory
`factory Color.named(...)` returns an instance it chooses, instead of always creating a fresh one.
private constructor
`Color._(...)` is a library-private generative constructor the factory uses to build values.
dispatch and fallback
The factory inspects its argument and picks a case, with a `default` branch for unknown inputs.