Factory and const Constructors
Cache, return subtypes, or build compile-time objects.
What a factory Constructor Is
A factory constructor looks like a normal one but you control what it returns, so it does not have to build a brand-new object every time.
class Logger {
factory Logger() => _shared;
}factory Can Return a Cached Object
Because it returns rather than always creating, a factory can hand back a cached instance, perfect for singletons or pools.
class Logger {
static final _it = Logger._();
Logger._();
factory Logger() => _it;
}All lessons in this course
- Default and Parameterized Constructors
- Named Constructors for Clear Intent
- Initializer Lists and Redirecting
- Factory and const Constructors