null_check_on_nullable_type_parameter
Don't use null
check on a potentially nullable type parameter.
This rule is available as of Dart 2.12.
Rule sets: core, recommended, flutter
This rule has a quick fix available.
Details
#DON'T use null
check on a potentially nullable type parameter.
Given a generic type parameter T
which has a nullable bound (e.g., the default
bound of Object?
), it is very easy to introduce erroneous null
checks when
working with a variable of type T?
. Specifically, it is not uncommon to have
T? x;
and want to assert that x
has been set to a valid value of type T
.
A common mistake is to do so using x!
. This is almost always incorrect, since
if T
is a nullable type, x
may validly hold null
as a value of type T
.
BAD:
T run<T>(T callback()) {
T? result;
(() { result = callback(); })();
return result!;
}
GOOD:
T run<T>(T callback()) {
T? result;
(() { result = callback(); })();
return result as T;
}
Usage
#To enable the null_check_on_nullable_type_parameter
rule,
add null_check_on_nullable_type_parameter
under linter > rules in your
analysis_options.yaml
file:
linter:
rules:
- null_check_on_nullable_type_parameter
除非另有说明,文档之所提及适用于 Dart 3.5.4 版本,本页面最后更新时间: 2024-08-02。 查看文档源码 或者 报告页面问题。