mergeable_switch_cases
Reports a switch case whose body repeats an earlier case’s, where the two can be merged. Merge them into one case.
- Tier
- advisory
- Scope
- Dart
- Lowest preset
- strict
- Fix
- none
What it reports
Section titled “What it reports”A case of a switch statement or expression whose body is the same code as an earlier case’s, where merging them does not change which value goes where. That is when:
- the two cases stand next to each other, or
- they and every case between them match constants. A
defaultor_last can take an earlier case of constants.
Every name in the two bodies must refer to the same declaration and have the same static type in both. The violation is on the later case’s head (case …: or the pattern). Each case that repeats an earlier one is a violation, so a run of six equal cases is five.
It does not report:
- a body that only leaves, or only names or builds a value without computing it (
break;,return null;,=> -1,=> Colors.red,=> theme.colorScheme.primary,=> const Padding()). These read as a table of values; - a case with a comment in it or right after it;
- a case whose pattern declares a variable;
- a labelled case;
- in a
switchexpression, a case with awhenclause; - bodies that read a member the case’s pattern made reachable, such as
case Failure(): show(state.error);besidecase Timeout(): show(state.error);. The merged case would knowstateonly by its own type.
One body written twice has to be changed twice. Merged, the cases say that they do the same.
Example
Section titled “Example”switch (state) { case AuthSuccess(): LoadingOverlay.hide(); case AuthFailure(): LoadingOverlay.hide(); case AuthLoading(): LoadingOverlay.show();}switch (state) { case AuthSuccess() || AuthFailure(): LoadingOverlay.hide(); case AuthLoading(): LoadingOverlay.show();}Rule parameters
Section titled “Rule parameters”Set under the assay: key of the project’s root analysis_options.yaml.
| Rule parameter | Default | Effect |
|---|---|---|
enabled |
true |
false switches the rule off for the whole project. |
exclude |
[] |
Path globs where the rule is silent. |
Suppressing it
Section titled “Suppressing it”Write why on the line directly above the suppression:
// Why it stays as written here.// ignore: mergeable_switch_cases// ignore_for_file: assay/mergeable_switch_cases silences it in a whole file, and the prefixed // ignore: assay/mergeable_switch_cases works too. See Suppressions.