null_check_on_nullable_type_parameter
Don't use null check on a potentially nullable type parameter.
此规则自 Dart 2.12 版本起可用。
_规则集:core , recommended , flutter _
此规则提供 快速修复 。
详情
#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;
}使用方法
#要启用 null_check_on_nullable_type_parameter 规则,请在你的 analysis_options.yaml 文件中,在 linter > rules 下添加 null_check_on_nullable_type_parameter :
linter:
rules:
- null_check_on_nullable_type_parameter除非另有说明,否则本网站上的文档反映的是 Dart 3.6.0。页面最后更新于 2025-02-05。 查看源代码 或 报告问题.