Pattern matching

suggest change

Introduced in Dart 3.0, patterns represent a major evolution in the language. Patterns allow you to test the shape and contents of data (matching) and extract components into local variables (destructuring) in a single, expressive operation.


Pattern Contexts

Patterns can be used in several language contexts:

1. switch Expressions

Switch expressions return a value directly and enforce compile-time exhaustiveness:

String describeNumber(int n) {
  return switch (n) {
    0 => 'Zero',
    > 0 && <= 10 => 'Small positive',
    > 10 && <= 100 => 'Medium positive',
    > 100 => 'Large positive',
    _ => 'Negative' // Wildcard catch-all
  };
}

2. Guard Clauses with when

Use when to apply additional boolean preconditions to a pattern:

String checkAccess(String role, int clearanceLevel) {
  return switch ((role, clearanceLevel)) {
    ('admin', >= 5) => 'Full Access Granted',
    ('admin', _) => 'Limited Admin Access',
    ('user', > 0) when clearanceLevel % 2 == 0 => 'Even Clearance Access',
    _ => 'Access Denied'
  };
}

3. Variable Declaration and Destructuring

Destructure records, lists, or objects directly when declaring variables:

(double, double) getCoordinates() => (37.7749, -122.4194);

void main() {
  // Destructure a record
  final (latitude, longitude) = getCoordinates();
  print('Lat: $latitude, Lon: $longitude');

  // Destructure a list
  final numbers = [10, 20, 30, 40];
  final [first, second, ...rest] = numbers;
  print('First: $first, Second: $second, Rest: $rest'); // 10, 20, [30, 40]
}

4. if-case Statements

The if-case construct conditionally matches and binds variables only if the target matches the pattern:

void handleApiResponse(dynamic response) {
  if (response case {'status': 'success', 'data': {'userId': int id, 'name': String name}}) {
    print('User #$id verified: $name');
  } else if (response case {'status': 'error', 'message': String errorMsg}) {
    print('API Error: $errorMsg');
  } else {
    print('Unexpected payload structure.');
  }
}

5. In Loops

Destructure entries seamlessly inside loops:

void main() {
  final scores = {'Alice': 95, 'Bob': 88, 'Charlie': 92};

  // Destructure MapEntry key and value using shorthand syntax
  for (final MapEntry(:key, :value) in scores.entries) {
    print('$key scored $value points.');
  }
}

Pattern Types

Object Patterns

Inspect class fields without manual casting or field extraction:

class Order {
  final int id;
  final double amount;
  final bool isVip;

  Order({required this.id, required this.amount, this.isVip = false});
}

void processOrder(Order order) {
  switch (order) {
    case Order(isVip: true, amount: > 1000):
      print('Expedited VIP White-Glove Shipping for order #${order.id}');
    case Order(amount: <= 0):
      print('Invalid order amount!');
    case Order(:var amount):
      print('Standard shipping for \$$amount');
  }
}

Null-Check (?) and Null-Assert (!) Patterns

void printFirstOrNull(List<String?> items) {
  switch (items) {
    // Matches only if first item is non-null
    case [var first?, ...]:
      print('First item: ${first.toUpperCase()}');
    case [null, ...]:
      print('First item is explicitly null');
    case []:
      print('List is empty');
  }
}

Exhaustive Pattern Matching with sealed Classes

Marking a class as sealed restricts all subclasses to the same library file. When pattern matching on a sealed hierarchy, the compiler guarantees that every possible case is handled:

sealed class NetworkState {}

class Loading extends NetworkState {}
class Success extends NetworkState {
  final String data;
  Success(this.data);
}
class Failure extends NetworkState {
  final String error;
  Failure(this.error);
}

// The compiler verifies that Loading, Success, and Failure are all covered!
String renderUI(NetworkState state) {
  return switch (state) {
    Loading() => 'Displaying spinner...',
    Success(:final data) => 'Rendering data: $data',
    Failure(:final error) => 'Displaying error: $error',
  };
}

Benefit: If you add a new subclass (such as OfflineState extends NetworkState), the Dart compiler will raise an error on every switch expression in your codebase until you handle the new case.


Best Practices

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents