const keyword that enables the creation of immutable, compile-time constant objects. When invoked in a constant context, it yields a canonicalized instance, meaning multiple instantiations with identical arguments reference the exact same memory address.
Syntax and Declaration
To define a constant constructor, prefix the constructor declaration withconst.
Structural Constraints
Dart enforces strict compile-time rules for classes utilizing constant constructors:- Immutable State: All instance variables within the class must be declared as
final. Furthermore, fields cannot be declared aslate; evenlate finalinstance variables are strictly prohibited. - No Execution Body: The constructor cannot possess a block body (
{}). State initialization must occur exclusively through formal parameters (this.field) or an initializer list. - Potentially Constant Initializers: Expressions within the initializer list must be potentially constant expressions. Because constant constructors can be invoked at runtime, these expressions only evaluate as compile-time constants when the constructor itself is invoked in a constant context. Otherwise, they evaluate at runtime using the provided non-constant arguments.
- Inheritance Chain: If the class extends a superclass, the superclass must also expose a constant constructor. The subclass must invoke it, either explicitly via a
supercall in the initializer list, or implicitly if the superclass provides an unnamed, no-argument constant constructor.
Instantiation and Canonicalization
A constant constructor can be invoked in two ways, fundamentally altering its memory allocation behavior: 1. Compile-Time Constant (Canonicalized) When invoked with theconst keyword (or inferred within a constant context), Dart evaluates the object at compile time. Identical arguments yield the exact same instance. All arguments passed to the constructor must also be compile-time constants.
const keyword. This bypasses compile-time evaluation and canonicalization, allocating a new, distinct object in memory at runtime, though its fields remain immutable.
Initializer List Mechanics
When using an initializer list with a constant constructor, operations are restricted to potentially constant expressions. You cannot call instance methods, invoke non-constant functions, or access non-constant values during initialization.Factory Constant Constructors
Afactory constructor can also be declared as const, provided it redirects to another constant constructor. It cannot execute arbitrary logic or return a cached instance manually, as the canonicalization is handled entirely by the Dart compiler.
Tired of Poor Dart Skills? Fix That With Deep Grasping!Learn More





