npx skills add ...
npx skills add dart-lang/skills --skill dart-use-pattern-matching
Applies Dart 3 pattern matching, switch expressions, and destructuring idiomatically to validate data schemas, handle algebraic data types, and decompose control flow. Use when refactoring complex if-else chains, parsing polymorphic JSON or API responses, destructuring Records or Maps, or enforcing exhaustiveness on sealed classes. Don't use for simple boolean conditions, single-variable type promotion (use `is`), or basic collection filtering.
npx skills add dart-lang/skills --skill dart-use-pattern-matching
Apply specific pattern types based on the data structure and desired outcome. Follow these conditional guidelines:
switch expressions over map discriminant keys to deserialize into sealed class hierarchies.sealed classes to ensure exhaustiveness.>=, <=) and Logical-and (&&) patterns within switch arms.||) patterns to share a single case body or guard clause._) or a non-matching Rest element (...) in collections.Select the appropriate switch construct based on the execution context:
switch (value) { pattern => expression, }switch (value) { case pattern: statements; }break keyword required).Implement patterns using the following syntax and rules:
||): pattern1 || pattern2. Both branches must define the exact same set of variables.&&): pattern1 && pattern2. Branches must not define overlapping variables.==, !=, <, >, <=, >= followed by a constant expression.as): pattern as Type. Throws if the value does not match the type. Use to forcibly assert types during destructuring.?): pattern?. Fails the match if the value is null. Binds the variable to the non-nullable base type.!): pattern!. Throws if the value is null.var name or Type name. Binds the matched value to a new local variable._): Matches any value and discards it.[pattern1, pattern2]. Matches lists of exact length unless a Rest element (... or ...var rest) is used.{"key": pattern}. Matches maps containing the specified keys. Ignores unmatched keys.(pattern1, named: pattern2). Matches records of the exact shape. Use :var name to infer the getter name.ClassName(field: pattern). Matches instances of ClassName. Use :var field to infer the getter name.Pattern matching and switch expressions should simplify code, not add syntactic overhead. Observe the following boundaries:
is Type Promotion over if-case for Single Promotable VariablesWhen checking or promoting a single variable, use standard is checks instead of if-case patterns that introduce shadow aliases.
When mapping or returning values where both null and a type T are valid and handled identically, match the nullable type T? directly rather than creating redundant null arms.
Do not use if-case in loops or deserialization to filter elements if malformed data should trigger an error or diagnostic warning.
if (x is T) instead of a switch statement with only 1 case and default: break;.condition ? a : b) instead of switch (condition) { true => a, false => b }.Use standard property access (user.name) rather than object pattern destructuring (final User(:name) = user;) when reading a single property on a known non-null instance.
if-case for Standalone Scalar ComparisonsUse standard boolean operators (if (code >= 200 && code < 300)) instead of if (code case >= 200 && < 300) for standalone conditions. Reserve relational patterns for multi-arm switch tables.
Copy this checklist to track progress when implementing complex pattern matching logic:
var x, :var y).when condition) for logic that cannot be expressed via patterns._) or default clause (if not using a sealed class).dart analyze).containsKey semantics) vs explicit null values.When switching over sealed classes or enums, ensure all subtypes are handled at compile time:
dart analyze._) arm if a default fallback or error is acceptable.Because dart analyze cannot statically verify dynamic Map<String, dynamic> keys, validate runtime pattern semantics explicitly:
null: A map pattern {'key': String? val} checks map.containsKey('key'). If 'key' is omitted from the JSON payload, the pattern fails to match at runtime even though String? is nullable. Extract optional keys from the validated map directly (map['key'] as String?)._ => throw FormatException(...) arm rather than silently failing an if-case check.Use Map patterns with switch expressions to validate tagged JSON payloads and
construct sealed class hierarchies. See
examples/json_patterns.dart for an executable
implementation demonstrating tagged ApiResponse parsing into SuccessResponse
and ErrorResponse.
Use nested Map and List patterns to validate required schema structure and
extract collections in a single step. See
examples/json_patterns.dart for an executable
implementation of processUserPayload.
Map patterns check for key existence (containsKey). If an optional JSON key
might be omitted entirely from the payload (rather than explicitly passed as
'key': null), destructure required keys via the pattern and extract optional
fields directly from the matched submap.
Use Object patterns with switch expressions to handle family types exhaustively.
Use variable assignment patterns to swap values or extract record fields without temporary variables.
Use when to evaluate arbitrary conditions after a pattern matches.