Rules / Suspicious / no-duplicate-case-values
no-duplicate-case-values
Flags a switch case whose value duplicates an earlier case in the same
switch.
Two cases with the same constant value can never both be reachable — Dart
dispatches to the first, so the later duplicate is dead code and usually
signals a paste that was never edited to its intended value. Literal cases
(null, bool, int, double, string, and their negations) and named constant
references are compared by value, and the duplicate occurrence is reported.
Give the redundant case its intended distinct value, or remove it.
Invalid
example.dartdart
// Bad: switch with duplicate case values
void processCode(int code) {
switch (code) {
case 1:
print('first');
break;
case 1:
print('duplicate');
break;
case 2:
print('second');
break;
}
}
// Bad: duplicate string cases
void processStatus(String status) {
switch (status) {
case 'active':
print('Active');
break;
case 'active':
print('Also active');
break;
case 'inactive':
print('Inactive');
break;
}
}
// Bad: duplicate boolean cases
void processBool(bool flag) {
switch (flag) {
case true:
print('True branch');
break;
case true:
print('Duplicate true');
break;
case false:
print('False branch');
break;
}
}
// Bad: double duplicate cases
void processDouble(double value) {
switch (value) {
case 1.5:
print('One point five');
break;
case 2.5:
print('Two point five');
break;
case 1.5:
print('Duplicate 1.5');
break;
case 2.5:
print('Duplicate 2.5');
break;
}
}
Duplicate case value in switch statement.
Duplicate case value in switch statement.
21 break;
22 case 'active':
∙
Duplicate case value in switch statement.
Duplicate case value in switch statement.
Duplicate case value in switch statement.
Valid
example.dartdart
// Good: all case labels are unique
void processCode(int code) {
switch (code) {
case 1:
print('first');
break;
case 2:
print('second');
break;
case 3:
print('third');
break;
}
}
// Good: unique string cases
void processStatus(String status) {
switch (status) {
case 'active':
print('Active');
break;
case 'inactive':
print('Inactive');
break;
case 'pending':
print('Pending');
break;
}
}
// Good: boolean cases without duplication
void handleBool(bool value) {
switch (value) {
case true:
print('True');
break;
case false:
print('False');
break;
}
}
// Good: unique double values
void handleDouble(double value) {
switch (value) {
case 1.5:
print('One point five');
break;
case 2.5:
print('Two point five');
break;
case 3.5:
print('Three point five');
break;
}
}
// Good: unique negative numbers
void handleNegative(int n) {
switch (n) {
case -1:
print('Negative one');
break;
case -2:
print('Negative two');
break;
case 0:
print('Zero');
break;
case 1:
print('One');
break;
}
}
How to configure
Set the severity of no-duplicate-case-values in your falcon.json:
falcon.jsonjson
{
"linter": {
"rules": {
"suspicious": {
"no-duplicate-case-values": "error"
}
}
}
}