avoid_ as
Avoid using as
.
Details
#NOTE: This rule was removed from the SDK in Dart 3; it is no longer functional. Its advice is compiler-specific and mostly obsolete with null safety.
AVOID using as
.
If you know the type is correct, use an assertion or assign to a more
narrowly-typed variable (this avoids the type check in release mode;
as
is not
compiled out in release mode). If you don't know whether the type is
correct, check using
is
(this avoids the exception that
as
raises).
BAD:
(pm as Person).firstName = 'Seth';
GOOD:
if (pm is Person)
pm.firstName = 'Seth';
but certainly not
BAD:
try {
(pm as Person).firstName = 'Seth';
} on CastError { }
Note that an exception is made in the case of
dynamic
since the cast has no
performance impact.
OK:
HasScrollDirection scrollable = renderObject as dynamic;
Enable
#
To enable the
avoid_as
rule, add
avoid_as
under
linter > rules
in your
analysis_options.yaml
file:
linter:
rules:
- avoid_as
If you're instead using the YAML map syntax to configure linter rules,
add
avoid_as: true
under
linter > rules:
linter:
rules:
avoid_as: true
Unless stated otherwise, the documentation on this site reflects Dart 3.9.2. Report an issue.