Skip to main content

avoid-type-casts

added in: 1.22.0
⚙️
Pro+

Warns about any usages of the as operator.

Incorrect usages of the as operator can lead to runtime exceptions. To avoid that, consider creating a local variable and ensuring its type with the is operator.

⚙️ Config

Set only-dynamic (default is false) to highlight only type casts for variables with the dynamic type (example).

analysis_options.yaml
dart_code_metrics:
rules:
- avoid-type-casts:
only-dynamic: false

Example

❌ Bad:

void fn() {
dynamic a = 3;
final s = a as String; // LINT: Avoid 'as' casts. Try creating a local variable and checking the type with 'is' first.

int b = 2;

final s = b as String; // LINT: Avoid 'as' casts. Try creating a local variable and checking the type with 'is' first.
if (b case String() as Object) {} // LINT: Avoid 'as' casts. Try creating a local variable and checking the type with 'is' first.
}

✅ Good:

void fn(List<String> values) {
dynamic a = 3;
if (a is String) {
...
}
}

Example with "only-dynamic"

Config
analysis_options.yaml
dart_code_metrics:
rules:
- avoid-type-casts:
only-dynamic: true

❌ Bad:

void fn() {
dynamic a = 3;
final s = a as String; // LINT: Avoid 'as' casts. Try creating a local variable and checking the type with 'is' first.
}

Additional Resources