Interview frequency: …
Short answer
A generative constructor creates an instance of the same class, while a factory can return an existing instance, an instance of a subclass, or run selection logic before returning.
Explanation
Use a generative constructor when you want to create an object and initialize its fields directly. A factory has no direct access to this before returning, but it suits caching, parsing, or choosing an implementation. Having a factory does not automatically mean there is a singleton; the decision depends on the class logic.
Code example
class User {
final String id;
User._(this.id);
factory User.fromJson(Map<String, Object?> json) {
return User._(json["id"]! as String);
}
}Common mistakes
- Treating a factory as always a singleton.
- Forgetting that a factory cannot use this before the object is created.