factory constructor is a specialized constructor implementation that is not required to generate a new instance of its enclosing class upon every invocation. Unlike a generative constructor, which automatically handles memory allocation and field initialization, a factory constructor functions similarly to a static method that must explicitly return an instance of the class or a compatible subtype.
Syntax and Structure
A factory constructor is declared using thefactory keyword. It operates without access to the instance pointer (this). While generative constructors have no return type, a factory constructor effectively has a return type matching the enclosing class and must explicitly return a value. Despite these internal structural differences, the invocation syntax for the consumer remains identical to that of a generative constructor.
Operational Mechanics
- Explicit Return: The body of a factory constructor is not restricted to creating a new object. It must, however, terminate by explicitly returning an instance of the enclosing class (or a subtype) or by throwing an exception.
- Static Context: Factory constructors operate without an instance context. Consequently, they cannot access instance members or the
thiskeyword. - No Initializer Lists: Because factory constructors do not handle the memory allocation phase directly, they cannot utilize initializer lists (the colon syntax
: field = value) used by generative constructors. - Polymorphism: A factory constructor is permitted to return an instance of a subtype of the enclosing class, allowing for polymorphic instantiation behavior hidden behind a single constructor interface.
Redirecting Factory Constructors
A factory constructor can delegate the instantiation logic entirely to another constructor using a redirecting syntax. This is permissible only if the target constructor returns an instance that is a subtype of the factory’s enclosing class. Syntax:Subscription redirects to the generative constructor of its subclass, PremiumSubscription.
Const Factory Constructors
A factory constructor can be declaredconst only if it is a redirecting factory constructor. It cannot have a body. The target of the redirection must be a const constructor, which may be either a const generative constructor or another const factory constructor. The redirection chain must eventually resolve to a const generative constructor.
Master Dart with Deep Grasping Methodology!Learn More





