Dart LanguageIntermediate30 XP5 min read
What are factory constructors in Dart and what are the 3 main patterns?
TL;DR: Factory constructors can return existing instances (caching/singleton), return subtype instances (polymorphic construction), or parse external data (fromJson). Unlike regular constructors, they can return different types.
Full Answer
- ▸Pattern 1 — Cached/Singleton: factory returns the same cached instance
- ▸Pattern 2 — Subtype dispatch: factory returns an appropriate subclass
- ▸Pattern 3 — fromJson: parses external data into the object
💡
factory constructors differ from regular constructors: they cannot use 'this' directly, cannot initialize final fields in the initializer list, and can return any instance (including pre-existing ones).
Code Examples
dartThree factory constructor patterns
Output
true Alice, 30
Interview Tip
💡
The fromJson pattern is ubiquitous in Dart. json_serializable generates factory User.fromJson(...) and Map<String, dynamic> toJson() for you, but knowing how to write them manually shows deep Dart knowledge.
#factory#constructor#singleton#fromjson#cache