Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

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:
TypeName(propertyName: subpattern, propertyName: subpattern)

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.
// Explicitly binding the 'title' getter to a new variable 'docTitle'
final Document(title: docTitle, pageCount: count) = myDocument;

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.
// Equivalent to Document(title: title, pageCount: pageCount)
final Document(:title, :pageCount) = myDocument;

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.
// Matches a User whose 'address' property is an Address object 
// where the 'city' property matches the string 'Seattle'.
if (user case User(address: Address(city: 'Seattle'))) {
  // ...
}

// Extracts the length of the string returned by the 'name' getter
final User(name: String(:length)) = user;

Constant Subpatterns and Relational Operators

Object patterns can evaluate properties against constant values or relational patterns rather than just binding them to variables.
// Matches if the Shape is a Circle and its radius getter returns a value >= 10
if (shape case Circle(radius: >= 10)) {
  // ...
}
Master Dart with Deep Grasping Methodology!Learn More