avoid-unrelated-type-assertions
preset: recommended
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() {
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; // LINT: Avoid unrelated 'is' assertion. The result is always 'false'.
}
void patterns() {
if (animal case NotAnimal result) {} // LINT: Avoid unrelated 'case Type' assertion. The result is always 'false'.
if (animal case NotAnimal()) {} // LINT: Avoid unrelated 'case Type' assertion. The result is always 'false'.
}
}
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
}