Skip to content
Development
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

From plugin
flutter-agent-plugins
2.9k25 skills1 MCP
Install
$ npx -y skills add flutter/agent-plugins --skill dart-use-pattern-matching --agent claude-code

How it fires

How this skill gets triggered: by you, by Claude, or both.

  • Fires itselfAuto-invocation. Claude auto-loads it when your prompt matches the work.Auto-invocation is when the right skill fires by itself at the right moment, driven by a FLOW.md router and a hook, instead of you invoking it by name. It is the difference between a skill being installed and a skill actually getting used.Read the full definition →
  • You can call itInvoke it directly when you want it.
  • Slash command/dart-use-pattern-matching

Context preview

The summary Claude sees to decide when to auto-load this skill.

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

SKILL.md

dart-use-pattern-matching.SKILL.md
name: dart-use-pattern-matching
description: >-
  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.
metadata:
  model: models/gemini-3.1-pro-preview
  last_modified: Sun, 06 Sep 2026 06:43:00 GMT

Implementing Dart Patterns

Contents

  • [Pattern Selection Strategy](#pattern-selection-strategy)
  • [Switch Statements vs. Expressions](#switch-statements-vs-expressions)
  • [Core Pattern Implementations](#core-pattern-implementations)
  • [Pragmatic Balance & Anti-Patterns](#pragmatic-balance--anti-patterns)
  • [Workflows](#workflows)
  • [Examples](#examples)

Pattern Selection Strategy

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

  • **If validating and extracting from deserialized data (e.g., JSON):** Use Map, List, and Object patterns to validate schema structure and destructure properties in a single step.
  • **If handling polymorphic payloads or responses:** Use `switch` expressions over map discriminant keys to deserialize into `sealed` class hierarchies.
  • **If handling multiple return values:** Use Record patterns to destructure fields directly into local variables.
  • **If executing type-specific behavior (Algebraic Data Types):** Use Object patterns combined with `sealed` classes to ensure exhaustiveness.
  • **If matching numeric ranges or conditions:** Use Relational (`>=`, `<=`) and Logical-and (`&&`) patterns within switch arms.
  • **If multiple cases share logic:** Use Logical-or (`||`) patterns to share a single case body or guard clause.
  • **If ignoring specific values:** Use the Wildcard pattern (`_`) or a non-matching Rest element (`...`) in collections.

Switch Statements vs. Expressions

Select the appropriate switch construct based on the execution context:

  • **If producing a value:** Use a **switch expression**.
  • Syntax: `switch (value) { pattern => expression, }`
  • Rule: Each case must be a single expression. No implicit fallthrough. Must be exhaustive.
  • **If executing statements or side effects:** Use a **switch statement**.
  • Syntax: `switch (value) { case pattern: statements; }`
  • Rule: Empty cases fall through to the next case. Non-empty cases implicitly break (no `break` keyword required).

Core Pattern Implementations

Implement patterns using the following syntax and rules:

  • **Logical-or (`||`):** `pattern1 || pattern2`. Both branches must define the exact same set of variables.
  • **Logical-and (`&&`):** `pattern1 && pattern2`. Branches must *not* define overlapping variables.
  • **Relational:** `==`, `!=`, `<`, `>`, `<=`, `>=` followed by a constant expression.
  • **Cast (`as`):** `pattern as Type`. Throws if the value does not match the type. Use to forcibly assert types during destructuring.
  • **Null-check (`?`):** `pattern?`. Fails the match if the value is null. Binds the variable to the non-nullable base type.
  • **Null-assert (`!`):** `pattern!`. Throws if the value is null.
  • **Variable:** `var name` or `Type name`. Binds the matched value to a new local variable.
  • **Wildcard (`_`):** Matches any value and discards it.
  • **List:** `[pattern1, pattern2]`. Matches lists of exact length unless a Rest element (`...` or `...var rest`) is used.
  • **Map:** `{"key": pattern}`. Matches maps containing the specified keys. Ignores unmatched keys.
  • **Record:** `(pattern1, named: pattern2)`. Matches records of the exact shape. Use `:var name` to infer the getter name.
  • **Object:** `ClassName(field: pattern)`. Matches instances of `ClassName`. Use `:var field` to infer the getter name.

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.

  • **Prefer:**
    // ✅ 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);
      }
    }
  • **Avoid:**
    // ❌ 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.

  • **Prefer:**
    // ✅ Clean nullable pattern match
    switch (value) {
      final String? s => s,
      _ => throw FormatException('Invalid value: $value'),
    }
  • **Avoid:**
    // ❌ 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.

  • **Prefer:**
    // ✅ 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);
Read more
Ships withflutter-agent-plugins

Agent plugins for Flutter, maintained by the Flutter team. A collection of plugins designed to extend AI agent capabilities for Flutter development.

Get the whole plugin
Stats
2,959
Stars
179
Forks
Active
Maintenance
Dart
Language
BSD-3-Clause
License
18h ago
Last commit
6mo ago
Created

Repo: flutter/agent-plugins

Other skills on flutter-agent-plugins.