Skip to main content
A relational pattern compares a matched value against a given constant using standard relational operators. It evaluates to true if the boolean result of applying the operator between the matched value and the constant expression is true.

Syntax

The <relational_operator> can be any of the following: ==, !=, <, >, <=, or >=. The <constant_expression> must evaluate to a compile-time constant.

Mechanics and Behavior

  1. Constant Requirement: The operand on the right side of the relational operator must be a compile-time constant. Variables evaluated at runtime are not permitted.
  2. Static Type Safety: The Dart analyzer statically verifies that the relational operator is defined for the static type of the matched value. If the matched value is of a type that does not implement the specified operator, a compile-time error occurs.
  3. Evaluation Order: When matching a value v against a relational pattern op c, the expression evaluates exactly as v op c.
  4. Exhaustiveness Checking: Dart’s exhaustiveness checker does not reason about the mathematical completeness of relational patterns. Even if a set of relational patterns logically covers all possible values (e.g., < 0, == 0, > 0), the compiler cannot deduce this. A default case (such as _) is strictly required in switch expressions utilizing relational patterns to prevent a non_exhaustive_switch_expression compile-time error.

Code Examples

In a Switch Expression:
Combined with Logical Patterns: Relational patterns are frequently combined with logical AND (&&) or logical OR (||) patterns to define bounded ranges.
In an if-case Statement:

Operator Overloading

Relational patterns respect custom operator overloading. If a user-defined class overrides a relational operator (such as operator >), a relational pattern can be applied to instances of that class, provided the right-hand operand is a valid constant of the expected type.
Tired of Poor Dart Skills? Fix That With Deep Grasping!Learn More