Skills
Skill 13 of 31
Applies Dart 3 pattern matching, switch expressions, and destructuring idiomatically to validate data schemas, handle algebraic data types, and decompose control flow.
4 minutes · 934 words · 22 sections
Install
npx skills add flutter/agent-plugins --skill dart-use-pattern-matchingnpx skills add flutter/agent-plugins/plugin marketplace add flutter/agent-pluginsThe first command installs just this skill, by the name in its SKILL.md; the second installs the whole repository.
Apply specific pattern types based on the data structure and desired outcome. Follow these conditional guidelines:
switch expressions over map discriminant keys to deserialize into sealed class hierarchies.sealed classes to ensure exhaustiveness.>=, <=) and Logical-and (&&) patterns within switch arms.||) patterns to share a single case body or guard clause._) or a non-matching Rest element (...) in collections.Select the appropriate switch construct based on the execution context:
switch (value) { pattern => expression, }switch (value) { case pattern: statements; }break keyword required).Implement patterns using the following syntax and rules:
||): pattern1 || pattern2. Both branches must define the exact same set of variables.&&): pattern1 && pattern2. Branches must not define overlapping variables.==, !=, <, >, <=, >= followed by a constant expression.as): pattern as Type. Throws if the value does not match the type. Use to forcibly assert types during destructuring.?): pattern?. Fails the match if the value is null. Binds the variable to the non-nullable base type.!): pattern!. Throws if the value is null.var name or Type name. Binds the matched value to a new local variable._): Matches any value and discards it.[pattern1, pattern2]. Matches lists of exact length unless a Rest element (... or ...var rest) is used.{"key": pattern}. Matches maps containing the specified keys. Ignores unmatched keys.(pattern1, named: pattern2). Matches records of the exact shape. Use :var name to infer the getter name.ClassName(field: pattern). Matches instances of ClassName. Use :var field to infer the getter name.Pattern matching and switch expressions should simplify code, not add syntactic overhead. Observe the following boundaries:
is Type Promotion over if-case for Single Promotable VariablesWhen checking or promoting a single variable, use standard is checks instead of if-case patterns that introduce shadow aliases.
// ✅ 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);
}
}// ❌ 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);
}
}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.
// ✅ Clean nullable pattern match
switch (value) {
final String? s => s,
_ => throw FormatException('Invalid value: $value'),
}// ❌ Redundant separate null arm
switch (value) {
final String s => s,
null => null,
_ => throw FormatException('Invalid value: $value'),
}Do not use if-case in loops or deserialization to filter elements if malformed data should trigger an error or diagnostic warning.
// ✅ 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);
}// ❌ Silently ignores malformed items
for (final raw in rawTasks) {
if (raw case final Map<String, dynamic> taskMap) {
_applyTask(taskMap);
}
}if (x is T) instead of a switch statement with only 1 case and default: break;.condition ? a : b) instead of switch (condition) { true => a, false => b }.Use standard property access (user.name) rather than object pattern destructuring (final User(:name) = user;) when reading a single property on a known non-null instance.
if-case for Standalone Scalar ComparisonsUse 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.
Copy this checklist to track progress when implementing complex pattern matching logic:
var x, :var y).when condition) for logic that cannot be expressed via patterns._) or default clause (if not using a sealed class).dart analyze).containsKey semantics) vs explicit null values.When switching over sealed classes or enums, ensure all subtypes are handled at compile time:
dart analyze._) arm if a default fallback or error is acceptable.Because dart analyze cannot statically verify dynamic Map<String, dynamic> keys, validate runtime pattern semantics explicitly:
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?)._ => throw FormatException(...) arm rather than silently failing an if-case check.Use Map patterns with switch expressions to validate tagged JSON payloads and
construct sealed class hierarchies. See
examples/json_patterns.dart (opens in a new tab) for an executable
implementation demonstrating tagged ApiResponse parsing into SuccessResponse
and ErrorResponse.
Use nested Map and List patterns to validate required schema structure and
extract collections in a single step. See
examples/json_patterns.dart (opens in a new tab) 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.
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,
};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();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');
}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.
The verbatim description from this skill’s front matter — the string an agent matches on to decide whether to load it.
main, last pushed 17 September 2026.SKILL.md, not by matching a directory convention. 2 distinct layouts observed: .agents/agents/reidbaker-agent/skills/*/SKILL.md, skills/*/SKILL.md.h1 and no skipped levels:.claude-plugin/marketplace.json by Dart and Flutter Team, declaring 1 plugin. It is read for editorial metadata only — never as the skill index, which is always the repository tree./flutter/agent-plugins.md, and each skill at its own .md URL.1 file · 3 KB
Everything this skill ships beside its prose. All of it is set here, as a subchapter of skill 13.
Everything else published alongside the skill.