Dart use pattern matching

From flutter/agent-plugins · View interactive version

Dart use pattern matching is an AI agent skill from the GitHub repository flutter/agent-plugins. 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 Lists, URI/path segments, Stri

How to use this skill

Skill file

Implementing Dart Patterns

Contents

Pattern Selection Strategy

Apply specific pattern types based on the data structure and desired outcome. Follow these conditional guidelines:

Switch Statements vs. Expressions

Select the appropriate switch construct based on the execution context:

Core Pattern Implementations

Implement patterns using the following syntax and rules:

Pragmatic Balance & Anti-Patterns

Pattern matching and switch expressions should simplify code, not add syntactic overhead. Observe the following boundaries:

1. Prefer `is` Type Promotion over `if-case` for Single Promotable Variables

When checking or promoting a single variable, use standard is checks instead of if-case patterns that introduce shadow aliases.

```dart

// ✅ Promotes key directly in-place without extra variables

for (final MapEntry(:key, :value) in map.entries) {

if (key is String && value != null) {

process(key, value);

}

}

```

```dart

// ❌ Anti-pattern: Introduces unnecessary alias variable k

for (final MapEntry(:key, :value) in map.entries) {

if (key case final String k when value != null) {

process(k, value);

}

}

```

2. Consolidate Nullable Types in Switch Arms

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.

```dart

// ✅ Clean nullable pattern match

switch (value) {

final String? s => s,

_ => throw FormatException('Invalid value: $value'),

}

```

```dart

// ❌ Redundant separate null arm

switch (value) {

final String s => s,

null => null,

_ => throw FormatException('Invalid value: $value'),

}

```

3. Preserve Fast-Fail Validation (Do Not Silently Drop Data)

Do not use if-case in loops or deserialization to filter elements if malformed data should trigger an error or diagnostic warning.

```dart

// ✅ Fast-fail with explicit diagnostic error

for (final raw in rawTasks) {

if (raw is! Map<String, dynamic>) {

throw FormatException('Expected Map item, got ${raw.runtimeType}: $raw');

}

_applyTask(raw);

}

```

```dart

// ❌ Silently ignores malformed items

for (final raw in rawTasks) {

if (raw case final Map<String, dynamic> taskMap) {

_applyTask(taskMap);

}

}

```

4. Avoid Single-Case or Boolean Switches

5. Use Object Destructuring for Multi-Field Unpacking, Not Single Properties or Passthroughs

Use object or record destructuring when extracting 3+ fields used across multiple statements, iterating MapEntry(:key, :value) in map.entries loops, eliminating a single-use intermediate variable, or promoting nullable fields to local variables (:field! or :field with != null). Keep standard property/element access (config.field) when:

```dart

// ✅ Unpacks multiple fields and asserts non-nullability in one declaration

final RunSpec(:target, :device!, :verbose) = spec;

```

```dart

// ❌ Repetitive multi-line property extraction

final target = spec.target;

final device = spec.device!;

final verbose = spec.verbose;

```

6. Avoid `if-case` for Standalone Scalar Comparisons

Use 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.

Workflows

Task Progress: Implementing Pattern Matching

Copy this checklist to track progress when implementing complex pattern matching logic:

Feedback Loop 1: Exhaustiveness Checking (Static Verification)

When switching over sealed classes or enums, ensure all subtypes are handled at compile time:

  1. Run analyzer: Execute dart analyze.
  2. Review errors: Look for "The type 'X' is not exhaustively matched by the switch cases" or unreachable pattern arm warnings.
  3. Fix: Add the missing Object patterns for unhandled subtypes, or add an explicit wildcard (_) arm if a default fallback or error is acceptable.

Feedback Loop 2: Runtime Map & JSON Pattern Verification

Because dart analyze cannot statically verify dynamic Map<String, dynamic> keys, validate runtime pattern semantics explicitly:

  1. Omitted Keys vs. Explicit 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?).
  2. Fast-Fail Fallback: Ensure unmatched or malformed map structures hit an explicit _ => throw FormatException(...) arm rather than silently failing an if-case check.

Examples

Polymorphic JSON Deserialization (Discriminated Unions)

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.

Nested JSON Validation and Optional Fields

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.

List and Path Segment Destructuring

Use if-case with list rest elements (...final rest) to validate prefixes and

extract remaining elements without a 2-arm _ => null switch or manual .first

and .skip(1) indexing.

String? resolveAllowedAssetSubpath(List<String> segments) {
  if (segments case ['assets', ...final rest]
      when rest.isNotEmpty && !rest.contains('..')) {
    return rest.join('/');
  }
  return null;
}

Algebraic Data Types (Sealed Classes)

Use Object patterns with switch expressions to handle family types exhaustively.

sealed class Shape {}

class Square implements Shape {
  final double length;
  Square(this.length);
}

class Circle implements Shape {
  final double radius;
  Circle(this.radius);
}

// Switch expression guarantees exhaustiveness due to `sealed` modifier.
double calculateArea(Shape shape) => switch (shape) {
  Square(length: var l) => l * l,
  Circle(:var radius)   => math.pi * radius * radius,
};

Variable Swapping and Destructuring

Use variable assignment patterns to swap values or extract record fields without temporary variables.

var (a, b) = ('left', 'right');
(b, a) = (a, b); // Swap values

// Destructuring a function return
var (name, age) = getUserInfo();

Guard Clauses and Logical-or

Use when to evaluate arbitrary conditions after a pattern matches.

switch (shape) {
  case Square(length: var s) || Circle(radius: var s) when s > 0:
    print('Valid positive shape with dimension $s');
  case Square() || Circle():
    print('Zero or negative dimension shape');
}
Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.