ClassName.identifier). This mechanism allows a class to define multiple distinct constructors, distinguishing them by name rather than relying solely on parameter signatures.
Syntax
The syntax consists of the class name, a dot, and a unique identifier.Classification
Named constructors are categorized as either generative or factory constructors.1. Named Generative Constructors
A named generative constructor creates a new instance of the class. It initializes instance variables and executes an optional body. Initialization Rules Object creation occurs in two phases:- Initialization Phase: All non-nullable, non-
lateinstance variables must be initialized. This is achieved via initializing formals (e.g.,this.field) or the initializer list. - Body Execution Phase: The constructor body executes after the instance is fully initialized. Assignments within the body are valid for any non-final field, provided the field was correctly initialized during the first phase.
2. Named Factory Constructors
A named constructor prefixed with thefactory keyword does not implicitly create a new instance of the class. Instead, it must explicitly return an instance of the class or a subtype.
Factory constructors do not have access to this and cannot use initializer lists to set instance fields directly. A factory constructor must return a non-nullable instance; returning null results in a compile-time error.
Delegation and Chaining
Redirecting Constructors
A named constructor can delegate initialization to another constructor within the same class using thethis keyword. A redirecting constructor cannot have a body.
Superclass Initialization
If a class inherits from a superclass, a named generative constructor must ensure the superclass is initialized. If the superclass does not provide a default (unnamed, no-argument) constructor, the subclass must explicitly invoke an available superclass constructor via thesuper keyword in the initializer list.
Scope and Visibility
Named constructors adhere to library privacy rules based on the identifier used:- Public:
ClassName.nameis accessible from any library. - Private:
ClassName._nameis accessible only within the library where the class is defined.
Inheritance Limitations
Constructors are not inherited. A subclass does not automatically acquire the named constructors of its superclass. To expose a named constructor in a subclass that matches the signature of a superclass constructor, the subclass must explicitly declare it and chain it to the superclass.Master Dart with Deep Grasping Methodology!Learn More





