prefer-switch-expression
Suggests converting switch statements to switch expressions.
In cases where all branches of a switch statement have a return statement or assign to the same variable, using a switch expression can make the code more compact and easier to understand.
⚙️ Config
Set ignore-fallthrough-cases
(default is false
) to suggest converting to a switch expression even if there are cases with no body.
analysis_options.yaml
dart_code_metrics:
rules:
- prefer-switch-expression:
ignore-fallthrough-cases: false
Example
❌ Bad:
AssetSensorType convert(AssetSensorCategory sensorCategory) {
// LINT: This switch statement can be converted to a switch expression.
switch (sensorCategory) {
case AssetSensorCategory.vibration:
return AssetSensorType.first;
case AssetSensorCategory.energy:
return AssetSensorType.second;
}
}
✅ Good:
AssetSensorType convert(AssetSensorCategory sensorCategory) {
return switch (sensorCategory) {
AssetSensorCategory.vibration => AssetSensorType.first,
AssetSensorCategory.energy => AssetSensorType.second,
};
}