Skip to main content

avoid-unnecessary-patterns

dart 3.0+
configurable
pro+

Warns when a pattern variable declaration does not affect the type of an existing local variable.

Such declarations are often missing a type annotation or a null-check pattern.

⚙️ Config

Set only-variables (default is true) to ignore patterns that are used a shorthand to a property access (example).

analysis_options.yaml
dart_code_metrics:
rules:
- avoid-unnecessary-patterns:
only-variables: true

Example

❌ Bad:

final value = 1;

void fn() {
// LINT: Avoid unnecessary patterns.
// Try changing it to a different pattern, for example, the null-check pattern (?).
if (value case final val) {}

// LINT: Avoid unnecessary patterns.
// Try changing it to a different pattern, for example, the null-check pattern (?).
if (value case var val) {}
}

✅ Good:

void fn() {
if (value case final val?) {}
if (value case final Object val) {}
if (value.sign case final sign) {}
}

Example with "only-variables"

Config
analysis_options.yaml
dart_code_metrics:
rules:
- avoid-unnecessary-patterns:
only-variables: false

❌ Bad:

void fn() {
// LINT: Avoid unnecessary patterns.
// Try changing it to a different pattern, for example, the null-check pattern (?).
if (value.sign case final sign) {} // now also highlighted
}

Additional Resources