dart-use-pattern-matching
Skill1 starsChanged 6 months agoBSD-3-ClauseView on GitHub
Use switch expressions and pattern matching where appropriate
5 other projects use a version of this, 2 of them edited.
Adopted by
Most recently taken up by
- dart-lang/skillsedited, first seen Oct 16, 2026
- zhouycheng/skillsword for word, first seen Oct 13, 2026
- enrique-lozano/Monekinword for word, first seen Oct 9, 2026
- flutter/skillsedited, first seen Oct 8, 2026
- hjdspace/SpaceCodeword for word, first seen Jul 21, 2026
Used with
Projects with it also use dart-setup-ffi-assets, dart-use-primary-constructors and 10 more.
Other files people use alongside this one.
Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
hjdspaceSkilldart-setup-ffi-assets
Guides agents in compiling and packaging C/C++ source code into dynamic or static libraries (Code Assets) using Dart's Native Assets hook system (via hook/build.dart and hook/link.dart utilizing package:hooks and package:native_toolchain_c). Use when a user asks to: 'setup native assets', 'compile C/C++ source code', 'bundle dynamic libraries', 'build native C code', 'link native assets', 'implement build.dart or link.dart hooks', or 'integrate C/C++ interop in Dart/Flutter'. Helps agents avoid manual toolchain orchestration and configures secure hash-validated binary downloads or advanced linker tree-shaking with package:record_use mapping.
Also in 4 projects that use this
hjdspaceSkilldart-use-primary-constructors
Help users write syntactically and semantically correct primary constructors in Dart, and migrate/use the new constructor syntax, empty-body semicolon syntax, in-body initializer list syntax, and abbreviated concise constructor syntax.
Also in 4 projects that use this
flutterSkilldart-use-doc-examples
How to inject external code examples into Dartdoc using the {@example} directive, and how to filter those files using #hide, #region, and #endregion tags.
Also in 3 projects that use this
flutterSkilldart-write-documentation
Rules and formatting guidelines for writing Dart /// API documentation and doc comments. Use when documenting Dart code, writing doc comments for any Dart declaration (libraries, classes, methods, variables, etc.), or when instructed to follow the Effective Dart documentation guidelines.
Also in 3 projects that use this
- +8 more from hjdspace
Other versions5 projects use a version of this.
Word for word · 3
- enrique-lozano/Monekin★ 268100% same
- hjdspace/SpaceCode★ 4100% same
- zhouycheng/skills★ 1100% same
Edited · 2
- flutter/skills★ 3.2k34% same
- dart-lang/skills★ 54834% same
Wrote their own version · 0
None found.
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository9 other files it gives its agents.
The file
Show its rules and text
We split this skill into the rules it gives an agent
14 rules. About 0 are common, 7 are distinctive, and 7 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈7
Distinctive · estimate
This author's own choices. Worth a look.
7
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 22
If handling multiple return values: Use Record patterns to destructure fields directly into local variables.
- Very specific: line 23
If executing type-specific behavior (Algebraic Data Types): Use Object patterns combined with sealed classes to ensure exhaustiveness.
- Very specific: line 24
If matching numeric ranges or conditions: Use Relational (>=, <=) and Logical-and (&&) patterns.
- Very specific: line 25
If multiple cases share logic: Use Logical-or (||) patterns to share a single case body or guard clause.
- Very specific: line 26
If ignoring specific values: Use the Wildcard pattern (_) or a non-matching Rest element (...) in collections.
- Distinctive: line 32
If producing a value: Use a switch expression.
- Distinctive: line 35
If executing statements or side effects: Use a switch statement.
- Very specific: line 70
When switching over sealed classes or enums, you must ensure all subtypes are handled.
- Distinctive: line 73
Review errors: Look for "The type 'X' is not exhaustively matched by the switch cases" errors.
- Very specific: line 74
Fix: Add the missing Object patterns for the unhandled subtypes, or add a Wildcard (_) case if a default fallback is acceptable.
- Distinctive: line 79
Use Map and List patterns to validate structure and extract data in a single step.
- Distinctive: line 98
Use Object patterns with switch expressions to handle family types exhaustively.
- Distinctive: line 122
Use variable assignment patterns to swap values or extract record fields without temporary variables.
- Very specific: line 134
Use when to evaluate arbitrary conditions after a pattern matches.
≈ “Common” is an estimate: at least 1 in 5 of the 350,495 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Implementing Dart Patterns
Contents
- Pattern Selection Strategy
- Switch Statements vs. Expressions
- Core Pattern Implementations
- 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 and List patterns to simultaneously check structure and destructure key-value pairs.
- 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
sealedclasses to ensure exhaustiveness. - If matching numeric ranges or conditions: Use Relational (
>=,<=) and Logical-and (&&) patterns. - 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.
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, 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). - Apply Guard clauses (
when condition) for logic that cannot be expressed via patterns. - Handle unmatched cases using a Wildcard (
_) ordefaultclause (if not using a sealed class). - Run exhaustiveness validator.
Feedback Loop: Exhaustiveness Checking
When switching over sealed classes or enums, you must ensure all subtypes are handled.
- Run validator: Execute
dart analyze. - Review errors: Look for "The type 'X' is not exhaustively matched by the switch cases" errors.
- Fix: Add the missing Object patterns for the unhandled subtypes, or add a Wildcard (
_) case if a default fallback is acceptable.
Examples
JSON Validation and Destructuring
Use Map and List patterns to validate structure and extract data in a single step.
Input:
var data = {
'user': ['Lily', 13],
};Implementation:
if (data case {'user': [String name, int age]}) {
print('User $name is $age years old.');
} else {
print('Invalid JSON structure.');
}Algebraic Data Types (Sealed Classes)
Use Object patterns with switch expressions to handle family types exhaustively.
Implementation:
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.
Implementation:
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.
Implementation:
switch (shape) {
case Square(size: var s) || Circle(size: var s) when s > 0:
print('Valid symmetric shape with size $s');
case Square() || Circle():
print('Invalid or empty shape');
default:
print('Unknown shape');
}Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

