MCPInstall

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 Lists, URI/path segments, String.split() tokens, 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.

Installs
14.6K
Last 24h
+193
Trending rank
#1250
Security
Pass

Install

Works with every agent the skills CLI supports.

npx skills add https://github.com/flutter/agent-plugins --skill dart-use-pattern-matching
  1. 01

    Install

    Run the command in your project. The CLI asks which agents to install for.

  2. 02

    Describe the task

    Ask your agent for something this skill covers. It loads dart-use-pattern-matching automatically when relevant.

  3. 03

    Review the result

    The agent follows the SKILL.md steps, scripts and references bundled with the skill.

Security audits

Independent scans of the skill's instructions and bundled files.

Gen Agent Trust Hub PassSAFE ·The skill provides safe and idiomatic guidelines for implementing Dart 3 pattern matching, switch expressions, and destructuring. It includes security-conscious coding examples and does not contain any malicious patterns.
Socket PassNo alerts
Snyk PassLOW ·Risk: LOW · No issues

SKILL.md

The instructions your agent reads when the skill is triggered.

Implementing Dart Patterns

Contents

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 inspecting URL/path segments (uri.pathSegments, p.split(path)) or String.split() tokens: Use List patterns with rest elements (['api', 'comments', ...], ['assets', ...final rest], [..., final parent, _]) instead of manual .length checks, .first, .skip(1), or length - N index arithmetic.
  • 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 unpacking multiple fields from an object or MapEntry: Use Object patterns (final Spec(:field1, :field2!) = spec;, for (final MapEntry(:key, :value) in map.entries)) when promoting nullable properties or unpacking 3+ fields used across multiple statements, rather than for single-call passthroughs.
  • 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);
    }
    
  • Avoid:
    // ❌ 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

  • Use if (x is T) instead of a switch statement with only 1 case and default: break;.
  • Use standard conditional ternary operators (condition ? a : b) instead of switch (condition) { true => a, false => b }.

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:

  • Reading a single property (user.name, or final CpuCallFrame(:url, :line) = node.callFrame; rather than nesting ProfileNode(callFrame: ...)).

  • Unpacking only 1–2 fields in a short getter/method, or unpacking fields only to pass them straight into a single constructor or function call.

  • Explicit local type annotations (specify_nonobvious_local_variable_types) require adding new library imports for marginal (1–2x) field reuse.

  • A long class name with renamed getters wraps a 2-field unpack across 3+ lines.

  • Any target variable is assigned to an outer-scoped variable (e.g., db = res.$1; before finally — final (db, ...) shadows outer db) or mixes final and mutable var locals.

  • Reading .first and .last on a list that may have length 1 ([first, ..., last] requires length >= 2; do not replace with multi-branch if-case).

  • Prefer:

    // ✅ Unpacks multiple fields and asserts non-nullability in one declaration
    final RunSpec(:target, :device!, :verbose) = spec;
    
  • Avoid:

    // ❌ 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:

  • Identify the data structure being evaluated (JSON, List/Segments, Record, Class, Enum).
  • Select the appropriate switch construct (Expression for values, Statement for side-effects).
  • Define the required patterns (Object, Map, List, Record).
  • Extract required data using Variable patterns (var x, :var y, ...final rest).
  • Apply Guard clauses (when condition) for logic that cannot be expressed via patterns.
  • Handle unmatched cases using a Wildcard (_) or default clause (if not using a sealed class).
  • Run static analyzer for exhaustiveness and dead code (dart analyze).
  • Verify runtime Map/JSON pattern behavior on omitted keys (containsKey semantics) vs explicit null values.

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');
}

FAQ

What does the dart-use-pattern-matching skill do?

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, String.split() tokens, 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.

How do I install dart-use-pattern-matching?

Run npx skills add https://github.com/flutter/agent-plugins --skill dart-use-pattern-matching in your project. The skills CLI detects the agents you use and copies the skill into the right folder. For Claude Code you can also place the skill folder at ~/.claude/skills/dart-use-pattern-matching/ (personal) or .claude/skills/dart-use-pattern-matching/ (project).

Which AI agents can use dart-use-pattern-matching?

Any agent that supports the open Agent Skills format (a folder with a SKILL.md file), including Claude Code, Codex, Cursor, GitHub Copilot, Gemini CLI, Windsurf, Cline, OpenCode and more.

Is dart-use-pattern-matching safe to install?

Security partners have reviewed it: Gen Agent Trust Hub passed; Socket passed; Snyk passed. As with any skill, read the SKILL.md and bundled scripts before installing.

Who maintains dart-use-pattern-matching?

It is published by flutter in flutter/agent-plugins. It has 14,581 recorded installs.

More from flutter/agent-plugins

View all →

Architects a Flutter application using the recommended layered approach (UI, Logic, Data). Use when structuring a new project or refactoring for scalability.

flutter-build-responsive-layout

flutter/agent-plugins

Use LayoutBuilder, MediaQuery, or Expanded/Flexible to create a layout that adapts to different screen sizes. Use when you need the UI to look good on both mobile and tablet/desktop form factors.

Frontend & Design42.8K installs

flutter-fix-layout-issues

flutter/agent-plugins

Fixes Flutter layout errors (overflows, unbounded constraints) using Dart and Flutter MCP tools. Use when addressing "RenderFlex overflowed", "Vertical viewport was given unbounded height", or similar layout issues.

Mobile40.2K installs

flutter-add-widget-test

flutter/agent-plugins

Implement a component-level test using WidgetTester to verify UI rendering and user interactions (tapping, scrolling, entering text). Use when validating that a specific widget displays correct data and responds to events as expected.

Testing & QA39.4K installs

flutter-add-integration-test

flutter/agent-plugins

Configures Flutter Driver for app interaction and converts MCP actions into permanent integration tests. Use when adding integration testing to a project, exploring UI components via MCP, or automating user flows with the integrationtest package.

Testing & QA38.4K installs

Configure MaterialApp.router using a package like gorouter for advanced URL-based navigation. Use when developing web applications or mobile apps that require specific deep linking and browser history support.

Mobile37.9K installs

Popular backend & apis skills

View category →

find-skills

vercel-labs/skills

Helps users discover and install agent skills when they ask questions like "how do I do X", "find a skill for X", "is there a skill that can...", or express interest in extending capabilities. This skill should be used when the user is looking for functionality that might exist as an installable skill.

OfficialBackend & APIs4.1M installs

entra-app-registration

microsoft/azure-skills

Guides Microsoft Entra ID app registration, OAuth 2.0 authentication, and MSAL integration. USE FOR: create app registration, register Azure AD app, configure OAuth, set up authentication, add API permissions, generate service principal, MSAL example, console app auth, Entra ID setup, Azure AD authentication. DO NOT USE FOR: Key Vault secrets (use azure-keyvault-expiration-audit), general Azure resource security guidance.

OfficialBackend & APIs566.7K installs

This skill should be used when the user wants to "write agent code", "build an agent with ADK", "add a tool", "create a callback", "define an agent", "use state management" — in a project that needs ADK (Agent Development Kit) API patterns and code examples. It provides a quick reference for agent types, tool definitions, orchestration patterns, callbacks, state management, the graph Workflow API, and reference recipes to study. Do NOT use for scaffolding (use google-agents-cli-scaffold) or deployment (use google-agents-cli-deploy).

Backend & APIs514.8K installs

embedded-captions

heygen-com/hyperframes

Add captions or subtitles to an existing single-subject talking-head video without editing the footage. Use for plain verbatim captions, cinematic captions embedded behind the subject, VFX captions, “炸/特效/酷炫字幕,” or a named identity from the 35-style catalog. Route by visual identity, not by backend engine. The quiet anchor rail is the default; embed every word only when the user explicitly wants a fully cinematic treatment. The workflow runs locally end to end, including transcription and subject matting; split multi-shot footage before applying it.

Backend & APIs453.3K installs

entra-agent-id

microsoft/azure-skills

Provision Microsoft Entra Agent Identity Blueprints, BlueprintPrincipals, and per-instance Agent Identities via Microsoft Graph, and configure OAuth 2.0 token exchange (fmipath, OBO, cross-tenant) including the Microsoft Entra SDK for AgentID sidecar. USE FOR: Agent Identity Blueprint, BlueprintPrincipal, agent OAuth, fmipath token exchange, agent OBO, Workload Identity Federation for agents, polyglot agent auth, Microsoft.Identity.Web.AgentIdentities. DO NOT USE FOR: standard Entra app registration (use entra-app-registration), Microsoft Foundry agent authoring (use microsoft-foundry).

OfficialBackend & APIs336.6K installs

neon

neondatabase/agent-skills

Overview of Neon, a complete set of cloud backend primitives around Lakebase Postgres: Auth, Object Storage, Functions, the AI Gateway, and Realtime. Start here to choose Neon for undecided login, files, APIs, and LLM calls, set up the CLI or MCP server, and follow the branch-first workflow. Use when building an app or backend on Neon, or when "Neon" or "Lakebase Postgres" is mentioned. Child skill neon-postgres wins for an existing DATABASEURL, SQL, schema, inspect, or search. Child skill neon-auth wins for login, users, sessions, identity routing, and Managed Better Auth setup. Child skill neon-realtime wins for live queries in reactive apps and agents. Also use for object storage, S3, buckets, serverless functions, function triggers, cron, AI gateway, LLM calls, realtime, logs, Loki, Grafana, observability, postgres, database, backend, Claimable Neon, neon.new, or a no-signup database.

Backend & APIs237.1K installs