Skip to content

avoid_wildcard_cases_with_enums

v0.8.0 Warning Pattern Matching

This rule is in the pedantic preset.

This rule flags a _ or default case in a switch over a non-nullable enum.

Switching over an enum without a catch-all gives you exhaustiveness checking for free. Add a constant to the enum and the compiler points at every switch that must now handle it — the change becomes a guided refactor rather than a hunt.

A wildcard case turns that off permanently. New constants silently fall into the catch-all and inherit whatever behaviour was written for the cases nobody had in mind. The bug appears at runtime, in whichever feature forgot to update.

The cost of listing constants explicitly is a few lines. The benefit is that the compiler maintains the list for you from then on.

See also: Dart: exhaustiveness checking

enum Status { active, inactive, pending }
String describe(Status status) => switch (status) {
Status.active => 'Active',
// A new constant silently becomes 'Other'
_ => 'Other',
};
String describe(Status status) => switch (status) {
Status.active => 'Active',
Status.inactive => 'Inactive',
Status.pending => 'Pending',
};

If several constants share behaviour, group them with || and keep the check:

String describe(Status status) => switch (status) {
Status.active => 'Active',
Status.inactive || Status.pending => 'Not active',
};

The rule stays silent in cases where a catch-all is legitimate:

  • Nullable enums. Status? needs a case for null, and _ is a reasonable way to write it.
  • Guarded wildcards. _ when flag => ... is conditional, so the compiler still checks the remaining constants.
  • Non-enum switches, including sealed class hierarchies, which are outside this rule’s scope.

This rule appears only in the pedantic preset because catch-all behavior is sometimes the contract, such as mapping every unsupported HTTP method to the same response.

Enable it by name:

many_lints.yaml
rules:
avoid_wildcard_cases_with_enums: true

To keep the rule on but skip certain paths, use per-rule exclude.