Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

The wildcard pattern (_) is a non-binding pattern that successfully matches any value or type without assigning it to a variable. It acts as an explicit discard mechanism during pattern matching, destructuring, and variable declaration, signaling to the compiler that the matched data is intentionally dropped from the lexical scope.

Syntax and Mechanics

The wildcard pattern is represented by a single underscore (_). Because it does not bind to a variable, it can be used multiple times within the same pattern or scope without causing naming collisions.

Standalone Wildcard

When used on its own, the wildcard matches any value. In switch statements or expressions, it functions as the exhaustive catch-all (replacing the legacy default keyword).
var result = switch (expression) {
  1 => 'One',
  2 => 'Two',
  _ => 'Other' // Matches any value not explicitly handled above
};

Typed Wildcard

The wildcard can be prefixed with a type annotation. This creates a pattern that matches only if the value is of the specified type, but still discards the value itself.
switch (dynamicValue) {
  case int _:
    print('Value is an integer, but the value is not bound.');
  case String _:
    print('Value is a string, but the value is not bound.');
}

Destructuring Collections

In list, map, and record patterns, the wildcard is used to structurally match the shape of the collection while selectively ignoring specific positional or named elements.
// Record destructuring: matches a 3-element record, discards the second element
var (first, _, third) = (1, 2, 3);

// List destructuring: matches a 4-element list, discards the middle two elements
var [start, _, _, end] = [10, 20, 30, 40];

// Map destructuring: matches the key 'b' but discards its value
var {'a': aVal, 'b': _} = {'a': 1, 'b': 2};

Technical Characteristics

  1. Non-Binding Nature: In pattern contexts (introduced in Dart 3.0), _ is strictly a structural placeholder. Attempting to read or reference _ as a variable after it has been used in a pattern results in a compile-time error.
  2. Multiplicity: Unlike standard variable identifiers, _ can be repeated infinitely within the same destructuring assignment or pattern match.
  3. Logical Operators: The wildcard is frequently combined with logical-or (|) and logical-and (&) patterns to satisfy structural requirements without polluting the local scope with unused variables.
// Using multiple wildcards in a single logical-or pattern
if (shape case (int _, double _) | (double _, int _)) {
  print('Matches a mixed numeric coordinate pair');
}
Master Dart with Deep Grasping Methodology!Learn More