Skip to main content

avoid-unnecessary-type-casts

added in: 1.6.0
Pro+
preset: recommended

Warns about unnecessary use of the as operator and cast method.

Unnecessary type casts are either a sign of a bug (another type should be used instead or the type hierarchy should include the expected type) or are redundant and can simply be removed.

Example

❌ Bad:

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

void main() {
final result = myList as List<int>; // LINT: Avoid unnecessary 'as' type cast.

final animal = Animal();
if (animal case HomeAnimal() as Animal) {} // LINT: Avoid unnecessary 'as' type cast.
}
}

class Animal {}

class HomeAnimal extends Animal {}

✅ Good:

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

void main() {
final result = myList;

final animal = Animal();
if (animal case HomeAnimal()) {}
}
}

Additional Resources