Skip to main content
A record pattern is a declarative construct in Dart used to match, validate, and destructure Record types. It allows developers to extract positional and named fields from a record into distinct variables and perform inline type checking within pattern-matching contexts like switch statements, if-case clauses, and variable declarations.

Syntax and Destructuring

Record patterns mirror the syntax of record expressions but operate in reverse, binding the extracted values to variables. Positional Fields Positional fields are matched strictly by their order within the record.
Named Fields Named fields are matched by their explicit identifiers, regardless of their order. The syntax requires the field name followed by a colon and the variable to bind.
Dart provides a syntactic shorthand for named fields when the bound variable name matches the field name. Prefixing the identifier with a colon implicitly creates a variable of the same name.

Pattern Matching and Control Flow

When used in control flow structures, record patterns act as predicates that evaluate to a boolean while simultaneously binding variables if the match succeeds.

Advanced Mechanics

Nested Subpatterns Record patterns can contain nested subpatterns, allowing for deep destructuring of complex, multi-layered data structures.
Wildcards The underscore _ acts as a wildcard pattern to discard specific positional fields without binding them to a variable or allocating memory for them.
Type Checking and Casting Patterns can enforce type constraints on individual fields. If the runtime type of the record’s field does not match the pattern’s type annotation, the match fails safely without throwing an exception.
Tired of Poor Dart Skills? Fix That With Deep Grasping!Learn More