avoid_constant_switches
v0.4.0 Warning Control Flow
Warns when a switch statement or switch expression evaluates a constant expression. Since the value never changes, the switch always takes the same branch, making all other cases dead code. This usually indicates a typo or a bug.
Why use this rule
Section titled “Why use this rule”Switching on a constant means only one branch can ever execute, turning the switch into expensive dead code. This is typically a mistake — the developer likely intended to switch on a variable or parameter instead of a compile-time constant. Catching this early prevents unreachable code from accumulating.
See also: Effective Dart: Usage
const _retryLimit = 4;
abstract final class Config { static const channel = 'stable';}
void bad() { // Switching on a static const field switch (Config.channel) { case 'stable': print('always'); case '2': print('never'); }
// Switching on a top-level const switch (_retryLimit) { case 4: print('always'); default: print('never'); }
// Switch expression on an integer literal final x = switch (42) { 42 => 'yes', _ => 'no', };}void good(int another) { // Parameter switch (another) { case 4: print('maybe'); default: print('maybe'); }
// Switch expression on parameter final x = switch (another) { 4 => 'ten', _ => 'other', };
// Method call result switch (another.toString()) { case '4': print('maybe'); }}Configuration
Section titled “Configuration”This rule is in the core preset, so it is on with preset: core,
preset: recommended or preset: opinionated.
To turn it off:
rules: avoid_constant_switches: falseTo keep the rule on but skip certain paths, use per-rule exclude.
Related rules
Section titled “Related rules”avoid_constant_conditions— Detect comparisons where both sides are constants.avoid_cascade_after_if_null— Detect cascades after if-null operators without parentheses.avoid_collapsible_if— Merge nested if statements with &&.avoid_contradictory_expressions— Detect logical AND conditions that always evaluate to false.