Skip to main content

avoid-unrelated-type-assertions

configurable
pro+

Warns about unrelated usages of the is operator and whereType method.

Unrelated type assertions are usually a sign of a bug (either the target variable or the used type should be different) and can lead to unexpected behavior.

⚙️ Config

Set ignore-mixins (default is false) to exclude mixins (example).

analysis_options.yaml
dart_code_metrics:
rules:
- avoid-unrelated-type-assertions:
ignore-mixins: false

Example

❌ Bad:

class Example {
final regularString = '';
final myList = <int>[1, 2, 3];

final Animal animal = Animal();

void main() {
// LINT: Avoid unrelated 'is' assertion. The result is always 'false'.
final result = regularString is int;
// LINT: Avoid unrelated 'is' assertion. The result is always 'false'.
final result2 = myList is List<String>;

// LINT: Avoid unrelated 'is' assertion. The result is always 'false'.
final result3 = animal is NotAnimal;
}

void patterns() {
// LINT: Avoid unrelated 'case Type' assertion. The result is always 'false'.
if (animal case NotAnimal result) {}
// LINT: Avoid unrelated 'case Type' assertion. The result is always 'false'.
if (animal case NotAnimal()) {}
}
}

class Animal {}

class NotAnimal {}

class HomeAnimal extends Animal {}

✅ Good:

class Example {
final regularString = '';
final myList = <int>[1, 2, 3];

final Animal animal = Animal();

void main() {
final result = regularString is String;
final result2 = myList is List<int>;

final result3 = animal is Object;
}

void patterns() {
final animal = Animal();

if (animal case HomeAnimal result) {}
if (animal case HomeAnimal()) {}
}
}

Example with "ignore-mixins"

Config
analysis_options.yaml
dart_code_metrics:
rules:
- avoid-unrelated-type-assertions:
ignore-mixins: true

✅ Good:

void main() {
final HomeAnimal homeAnimal = HomeAnimal();

final result = homeAnimal is WithLegs; // Correct, mixins are ignored
}

class Animal with WithLegs {}

class HomeAnimal extends Animal {}

mixin WithLegs {}

Known Limitations

The rule does not have access to all subclasses and their mixins and therefore in some cases will highlight such usages as incorrect.

class Parent {}

mixin Mixin {}

class Child with Mixin {}

void fn() {
final list = <Parent>[]; // List of 'Parents'

final result = list.whereType<Mixin>(); // Expected
}

Additional Resources