const keyword that enables the creation of canonicalized instances. When invoked in a constant context, the constructor produces an instance known at compile time, allowing the Dart compiler to deduplicate identical instances into a single memory address.
Syntax and Declaration Requirements
To declare a constant constructor, the class and the constructor must adhere to specific immutability constraints:constKeyword: The constructor declaration must be prefixed withconst.- Immutable State: All instance variables (fields) within the class must be declared as
final. - No
lateFields: Fields cannot be declared with thelatemodifier, aslateimplies runtime initialization. - No Block Body: The constructor cannot have a body (curly braces
{}). It must terminate with a semicolon, potentially following an initializer list. - Superclass Constraints: If the class inherits from a superclass, the superclass constructor being invoked must also be a constant constructor.
Initialization Lists and Potentially Constant Expressions
Constant constructors may use initializer lists to assign values to fields or call super constructors. However, expressions within the initializer list are restricted to potentially constant expressions. A potentially constant expression is an expression that can be evaluated at compile time if the constructor itself is invoked in a constant context. This allows the use of:- Literals (numbers, strings).
- Constructor parameters.
- Arithmetic operations involving other potentially constant expressions.
- Invocations of other constant constructors.
Invocation and Instantiation Contexts
A constant constructor behaves differently depending on the context in which it is invoked. There are three scenarios:- Explicit Constant Context: The constructor is explicitly invoked with the
constkeyword. This forces compile-time creation and canonicalization. - Implicit Constant Context: The constructor is invoked without the
constkeyword, but resides within a context that requires a constant (such as a variable declaredconstor inside aconstcollection literal). Dart infers theconstkeyword, resulting in a compile-time canonicalized instance. - Non-Constant Context: The constructor is invoked without
constin a context where a constant is not required (e.g., assigned to afinalorvarvariable). A new object is allocated at runtime.
Canonicalization
The primary mechanism of a constant constructor is canonicalization. The compiler ensures that for any given constant constructor invoked with identical arguments in a constant context, only one instance is created in memory. Variables holding constant instances with the same state refer to the exact same memory address.Master Dart with Deep Grasping Methodology!Learn More





