Skip to main content

avoid-type-casts

configurable
pro+

Warns about any usage 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;
// LINT: Avoid 'as' casts.
// Try creating a local variable and checking the type with 'is' first.
final s = a as String;

int b = 2;

// LINT: Avoid 'as' casts.
// Try creating a local variable and checking the type with 'is' first.
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) {}
}

✅ 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;
// LINT: Avoid 'as' casts.
// Try creating a local variable and checking the type with 'is' first.
final s = a as String;
}

Additional Resources