A constant pattern determines if a matched value is equal to a specific compile-time constant. It evaluates toDocumentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
true if the matched value and the constant are equivalent, strictly requiring the constant to have primitive equality.
Syntax
The syntax consists of a compile-time constant expression placed directly within a pattern matching context, such as aswitch statement, switch expression, or if-case statement.
The Primitive Equality Requirement
Dart strictly requires constant patterns to have primitive equality. A compile-time constant whose class overridesoperator == cannot be used as a constant pattern. The pattern matching mechanism relies on compiler-enforced identity or primitive equivalence rather than invoking a custom == method at runtime.
If a developer needs to match against a constant that belongs to a class overriding operator == (such as Point from dart:math), the constant pattern will fail to compile. Instead, the developer must use a relational pattern by explicitly prepending the equality operator:
Valid Constant Expressions
A constant pattern accepts expressions that Dart evaluates as compile-time constants, provided they meet the primitive equality rule. This includes:- Primitive Literals: Integers (
42), doubles (3.14), strings ('Dart'), booleans (true,false), andnull. (Note: WhileStringanddoubleoverride==, Dart’s specification explicitly grants them primitive equality status for pattern matching). - Named Constants: Variables explicitly declared with the
constmodifier, referencing primitive-equality types. - Enum Values: Specific members of an enumeration.
- Constant Constructors: Object instances created using a
constconstructor, strictly on classes that do not overrideoperator ==. - Constant Collections: Lists, sets, or maps instantiated with the
constkeyword.
Technical Mechanics
- Compile-Time Resolution: The pattern itself must be fully resolved at compile time.
finalvariables or runtime-evaluated expressions are invalid. - Canonicalization: Because constant patterns require primitive equality, Dart often relies on the canonicalization of
constinstances to perform rapid identity checks (identical()) under the hood. - Type Promotion: If a constant pattern matches, it does not inherently promote the type of the matched variable. The match guarantees value equivalence, not strict type identity.
Code Visualization
The following example demonstrates valid constant patterns, including a custom class that adheres to the primitive equality rule by not overridingoperator ==:
Master Dart with Deep Grasping Methodology!Learn More





