What are Patterns in Dart?
Introduced in Dart 3.0, patterns are a powerful feature that let you destructure data, test values, and bind variables in a concise and expressive way. Patterns can be used in several contexts: variable declarations (var (x, y) = point), switch statements and expressions, if-case statements, and for loops. Patterns bring many functional programming conveniences to Dart.
Basic Pattern Types
Dart supports a variety of pattern types. Here are the most common:
Wildcard Pattern (_)
The underscore _ matches any value but does not bind it to a variable. It's useful when you want to ignore a part of a structure.
Variable Pattern
A variable pattern binds a value to a new variable. The variable can be var, final, or a specific type.
Constant Pattern
Matches a value exactly against a constant. Useful in switch cases and if-case.
Logical Patterns (||, &&)
Combine subpatterns using || (or) and && (and). This allows you to match multiple possibilities.
Relational Patterns (<, >, <=, >=, ==)
Compare values using relational operators. Useful for ranges in patterns.
Cast Pattern (as)
Attempts to cast the value to a type. If the cast fails, the pattern does not match.
List Pattern
Destructures a list by matching elements. You can use _ to ignore elements and ... to match the rest.
Map Pattern
Destructures a map by matching key‑value pairs. Only the listed keys are extracted; extra keys are ignored.
Record Pattern
Destructures a record by matching its fields. Both positional and named fields can be matched.
Object Pattern
Matches against an object's type and extracts its fields using named getters (or properties). For example, you can extract the x and y fields from a Point instance.
Guard Pattern (when)
A guard is an extra condition that must be true for a pattern to match. It can be added to any pattern in a switch or if-case.
Pattern Usage in Switch
switch statements and switch expressions can now use patterns. Each case can be a pattern, and you can use guards.
Pattern Usage in if-case
if (value case pattern) allows you to conditionally match and bind variables in a single line.
Patterns in For Loops
You can destructure elements in for loops using patterns.
Key Takeaways
- Patterns enable destructuring, conditional matching, and variable binding in Dart 3+.
- Wildcard (
_), variable, constant, logical, relational, cast, list, map, record, object, and guard patterns.
- Wildcard (
- Patterns are used in
switch,if-case, variable declarations, andforloops.
- Patterns are used in
- Pattern matching makes code more readable and reduces boilerplate.