Skip to content

prefer_switch_expression

v0.3.0WarningFixConfigurableControl Flow

Warns when a switch statement can be converted to a switch expression. This applies when all branches either return a value or assign to the same variable, with each case containing exactly one statement.

Dart 3 introduced switch expressions as a more concise alternative to switch statements for simple value-producing switches. They reduce boilerplate (case, return, break), make it clear that the switch produces a value, and are easier to read when each branch is a single expression. The quick fix handles the conversion automatically.

See also: Switch expressions

// All cases return a value — use switch expression
DeliveryIcon iconForBad(DeliveryStage stage) {
switch (stage) {
case DeliveryStage.packed:
return DeliveryIcon.box;
case DeliveryStage.shipped:
return DeliveryIcon.truck;
case DeliveryStage.delivered:
return DeliveryIcon.home;
}
}
// All cases assign to the same variable
String getDescriptionBad(DeliveryIcon icon) {
String description;
switch (icon) {
case DeliveryIcon.box:
description = 'Waiting in the warehouse';
case DeliveryIcon.truck:
description = 'On the road';
case DeliveryIcon.home:
description = 'Dropped at the door';
}
return description;
}
// Switch expression with return
DeliveryIcon iconForGood(DeliveryStage stage) {
return switch (stage) {
DeliveryStage.packed => DeliveryIcon.box,
DeliveryStage.shipped => DeliveryIcon.truck,
DeliveryStage.delivered => DeliveryIcon.home,
};
}
// Switch expression with assignment
String getDescriptionGood(DeliveryIcon icon) {
final description = switch (icon) {
DeliveryIcon.box => 'Waiting in the warehouse',
DeliveryIcon.truck => 'On the road',
DeliveryIcon.home => 'Dropped at the door',
};
return description;
}
// Switch expression with default case (using wildcard)
String getNameGood(int value) {
return switch (value) {
1 => 'one',
2 => 'two',
_ => 'unknown',
};
}

This rule is in the opinionated preset, so it is on with preset: opinionated, or by name:

many_lints.yaml
rules:
prefer_switch_expression: true

To turn it off again:

many_lints.yaml
rules:
prefer_switch_expression: false

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

analysis_options.yaml
many_lints:
rules:
prefer_switch_expression:
allow_fallthrough_cases: true
Option Type Default Description
allow_fallthrough_cases bool false Also report switches where labels share a body. The quick fix merges them into a single `case a