Skip to main content
An object pattern matches a value against a specified type and destructures the object’s properties by invoking its getters. It allows developers to simultaneously perform type checking and extract specific fields into variables or evaluate them against further subpatterns.

Syntax

The explicit syntax requires the expected type, the property name (getter), and a subpattern to match against the property’s value:

Evaluation Mechanics

When an object pattern is evaluated against a value, Dart performs the following sequence of operations:
  1. Type Testing: The pattern checks if the incoming value is a subtype of TypeName. If the value is null (and the type is non-nullable) or of a different type, the match fails.
  2. Getter Invocation: If the type test succeeds, Dart invokes the specified getters (propertyName) on the matched object.
  3. Subpattern Matching: The values returned by the getters are evaluated against their corresponding subpatterns. If any subpattern fails to match, the entire object pattern fails.

Variable Binding and Destructuring

Object patterns are heavily used in variable declarations and assignments to extract data from an object into local variables.

Shorthand Syntax

If the subpattern is a variable pattern and you want the bound variable to have the exact same name as the object’s getter, Dart provides a syntactic shorthand using a colon (:) followed by the property name.

Nested Patterns

Because the right side of the colon is a subpattern, object patterns can be nested to arbitrary depths. This allows for complex validation and destructuring of object graphs in a single expression.

Constant Subpatterns and Relational Operators

Object patterns can evaluate properties against constant values or relational patterns rather than just binding them to variables.
Tired of Poor Dart Skills? Fix That With Deep Grasping!Learn More