Skip to content

prefer_switch_expression

v0.3.0 Warning Fix Control 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
AssetSensorType convertBad(AssetSensorCategory sensorCategory) {
switch (sensorCategory) {
case AssetSensorCategory.vibration:
return AssetSensorType.first;
case AssetSensorCategory.energy:
return AssetSensorType.second;
case AssetSensorCategory.temperature:
return AssetSensorType.third;
}
}
// All cases assign to the same variable
String getDescriptionBad(AssetSensorType type) {
String description;
switch (type) {
case AssetSensorType.first:
description = 'First sensor';
case AssetSensorType.second:
description = 'Second sensor';
case AssetSensorType.third:
description = 'Third sensor';
}
return description;
}
// Switch expression with return
AssetSensorType convertGood(AssetSensorCategory sensorCategory) {
return switch (sensorCategory) {
AssetSensorCategory.vibration => AssetSensorType.first,
AssetSensorCategory.energy => AssetSensorType.second,
AssetSensorCategory.temperature => AssetSensorType.third,
};
}
// Switch expression with assignment
String getDescriptionGood(AssetSensorType type) {
final description = switch (type) {
AssetSensorType.first => 'First sensor',
AssetSensorType.second => 'Second sensor',
AssetSensorType.third => 'Third sensor',
};
return description;
}
// Switch expression with default case (using wildcard)
String getNameGood(int value) {
return switch (value) {
1 => 'one',
2 => 'two',
_ => 'unknown',
};
}

To disable this rule:

plugins:
many_lints:
diagnostics:
prefer_switch_expression: false