dart-use-pattern-matching
БесплатноБез исполняемых скриптовНе проверенApplies Dart 3 pattern matching, switch expressions, and destructuring idiomatically to validate data schemas, handle algebraic data types, and decompose…
от flutter★ 3 224 звезды на GitHubОб этом скилле
Implementing Dart Patterns
Contents
- Pattern Selection Strategy
- Switch Statements vs. Expressions
- Core Pattern Implementations
- Pragmatic Balance & Anti-Patterns
- Workflows
- 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 inspecting URL/path segments (
uri.pathSegments,p.split(path)) orString.split()tokens: Use List patterns with rest elements (['api', 'comments', ...],['assets', ...final rest],[..., final parent, _]) instead of manual.lengthchecks,.first,.skip(1), orlength - Nindex arithmetic. - If handling polymorphic payloads or responses: Use
switchexpressions over map discriminant keys to deserialize intosealedclass 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
sealedclasses 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.
- Syntax:
- 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
breakkeyword required).
- Syntax:
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 nameorType 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 nameto infer the getter name. - Object:
ClassName(field: pattern). Matches instances ofClassName. Use:var fieldto 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
Установить dart-use-pattern-matching в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
FAQ
Что делает скилл 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.
Как установить скилл dart-use-pattern-matching?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл dart-use-pattern-matching запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
skill-creator
Create new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an…
от Anthropicdiscernment-nudge
After you give a substantive answer or draft that the user may act on — advice or recommendations, drafted artifacts such as goals, plans, pitches, proposals…
от Anthropicdata-consolidate
Joins the plant's scheduled exports and connector data into one working dataset — ERP items (NetSuite or Infor M3), sales orders, production work orders…
от Anthropicinspection-to-capa
Runs the quality chain end to end: writes the nonconformance against the requirement it violates, searches history at the moment of writing to say whether…
от Anthropic