For AI agents: A markdown version of this page is available at https://docs.datadoghq.com/security/code_security/static_analysis/static_analysis_rules/dart-code-quality/no-duplicate-case-values.md. A documentation index is available at /llms.txt.

Avoid duplicate case values in a switch

This product is not supported for your selected Datadog site. ().

Metadata

ID: dart-code-quality/no-duplicate-case-values

Language: Dart

Severity: Warning

Category: Code Style

Description

When two case clauses in the same switch share the same constant value, only the first one is reachable and the later one is dead code, which is usually a copy-paste mistake. Remove the duplicate case or correct its value so each case is distinct and reachable.

Non-Compliant Code Examples

void main(int x, String s, bool a) {
  switch (x) {
    case 1:
      print('one');
      break;
    case 2:
      print('two');
      break;
    case 1:
      print('duplicate one');
      break;
    case 2 when a:
      print('duplicate two');
      break;
  }

  switch (s) {
    case 'a':
      print('a');
      break;
    case 'a':
      print('duplicate a');
      break;
  }
}

Compliant Code Examples

void main(int x, String s, bool a, bool b) {
  switch (x) {
    case 1:
      print('one');
      break;
    case 2:
      print('two');
      break;
    default:
      print('other');
  }

  switch (s) {
    case 'a':
      print('a');
      break;
    case 'b':
      print('b');
      break;
  }

  switch (x) {
    case 1 when a:
      print('one-a');
      break;
    case 1 when b:
      print('one-b');
      break;
  }

  switch (x) {
    case 1:
      print('again');
      break;
  }

  // Guarded case before a plain case: the plain `case 1:` is still reachable
  // (it matches when the guard is false), so nothing is flagged.
  switch (x) {
    case 1 when a:
      print('one-a');
      break;
    case 1:
      print('one');
      break;
  }
}
https://static.datadoghq.com/static/images/logos/github_avatar.svg https://static.datadoghq.com/static/images/logos/vscode_avatar.svg jetbrains

Seamless integrations. Try Datadog Code Security