skills/dart/dart-use-pattern-matching/SKILL.md
Leverage switch expressions and Dart 3+ pattern matching to build clean, exhaustive, and type-safe control flows for algebraic data types, JSON parsing, and variable destructuring.
npx skillsauth add dhruvanbhalara/skills dart-use-pattern-matchingInstall this skill globally with one command. Works with Claude Code, Cursor, and Windsurf.
3 of 9 scanners reported clean
Some scanners were skipped, did not run, or reported a non-clean status. Review each row below.
Apply distinct pattern matching strategies based on the target data structure:
sealed class hierarchies with Object patterns in switch expressions to benefit from compile-time exhaustiveness checking.>=, <, etc.) and logical-and (&&) or logical-or (||) operators within switch cases.when keyword to assert dynamic conditions that cannot be expressed purely through static patterns.Choose the correct switch construct based on the operational context:
final result = switch (value) { pattern => expression, _ => fallback };switch (value) {
case pattern:
// statements
break; // Implicitly breaks, but can be added explicitly
}
Understand and apply standard Dart 3+ pattern syntaxes:
||): Combines patterns. Matches if either pattern succeeds. Both branches must define identical sets of variables.&&): Matches if both patterns succeed. Branches must not define overlapping variables.> 100, != 0).as): Asserts type transformations during destructuring (throws if type check fails).?): Filters out null values and binds variables to their non-nullable base types.!): Asserts that a value is non-nullable (throws if null).[var first, var second]). Use a rest element (...) to ignore trailing list elements.{'id': var id}). Ignores keys that are not explicitly matched.User(:final name)).Follow this checklist to implement clean pattern matching structures:
when expressions for conditional boundary checks._ fallback.dart analyze to ensure there are no unhandled cases or type mismatches.Validate structure and extract values in a single step using map destructuring.
void processPayload(Map<String, dynamic> payload) {
if (payload case {'status': 'success', 'data': [String title, int count]}) {
print('Product: $title, Inventory: $count');
} else {
print('Invalid payload structure received');
}
}
Leverage sealed classes to force exhaustive compile-time verification when executing domain logic.
sealed class NetworkState {}
class NetworkIdle extends NetworkState {}
class NetworkLoading extends NetworkState {}
class NetworkSuccess extends NetworkState {
final String response;
NetworkSuccess(this.response);
}
class NetworkFailure extends NetworkState {
final String error;
NetworkFailure(this.error);
}
// Compiler guarantees all sub-states are handled without requiring a default fallback
String getStatusMessage(NetworkState state) {
return switch (state) {
NetworkIdle() => 'Waiting to connect...',
NetworkLoading() => 'Loading data...',
NetworkSuccess(:final response) => 'Data loaded: $response',
NetworkFailure(:final error) => 'Failed: $error',
};
}
// Destructuring a positional and named return record:
(String name, {int age}) getUser() => ('Alice', age: 30);
void main() {
final (name, age: userAge) = getUser();
print('$name is $userAge years old');
// Value swapping without temp variables:
var (x, y) = (1, 2);
(y, x) = (x, y);
}
development
Perform REST API networking operations (GET, POST, PUT, DELETE) using the lightweight and robust standard `http` package, including platform configurations and background parsing models.
development
Configure internationalization and localization support using Flutter's built-in l10n system, App Resource Bundle (ARB) files, and ICU formatting syntax.
development
Create model classes with fromJson/toJson using dart:convert and Dart 3 pattern matching. Use when manually mapping JSON to classes, parsing HTTP responses, or choosing between manual and code-generated serialization.
data-ai
Diagnose and fix Flutter layout constraint violations (RenderFlex overflow, unbounded height/width, ParentData misuse). Use when encountering layout exceptions, yellow-black overflow stripes, or red error screens.