Skip to main content

avoid-shadowing

added in: 1.2.0
⚙️
Pro+
preset: recommended

Warns when a declaration name shadows another declaration with the same name in the current scope.

Shadowing an existing variable / parameter / field can lead to unexpected results, especially if the types of both declaration (shadowed and the new one) match.

⚙️ Config

Set ignore-static (default is false) to exclude static fields from the name scope.

Set ignore-fields (default is false) to exclude fields from the name scope.

Set ignore-parameters (default is false) to exclude parameters from the name scope.

Set ignored-names (default is empty) to ignore specific names (example).

analysis_options.yaml
dart_code_metrics:
rules:
- avoid-shadowing:
ignore-static: false
ignore-fields: false
ignore-parameters: false
ignored-names:
- some
- name

Example

❌ Bad:

class SomeClass {
final String content;

...

void method() {
// LINT: Identifier with the same name is already declared in the outer scope. Try renaming this identifier.
final content = ...;
}

// LINT: Identifier with the same name is already declared in the outer scope. Try renaming this identifier.
void anotherMethod(String content) {
...
}

void records() {
final declarations = <(int, String)>{};

var length = 0;

// LINT: Identifier with the same name is already declared in the outer scope. Try renaming this identifier.
if (declarations case Set(:final length)) {
...
}

// LINT: Identifier with the same name is already declared in the outer scope. Try renaming this identifier.
final Set(length: final length) = declarations;
}
}

✅ Good:

class SomeClass {
final String content;

...

void method() {
final localContent = ...;
}

void anotherMethod(String contentParam) {
...
}

void records() {
final declarations = <(int, String)>{};

var length = 0;

if (declarations case Set(length: final someLength)) {
...
}

final Set(length: final someLength) = declarations;
}
}

Example with "ignored-names"

Config
analysis_options.yaml
dart_code_metrics:
rules:
- avoid-shadowing:
ignored-names:
- content

✅ Good:

class SomeClass {
final String content;

...

void method() {
final content = ...; // Correct, 'content' is ignored
}

// Correct, 'content' is ignored
void anotherMethod(String content) {
...
}
}