健全的空安全
Dart 空安全简介
The Dart language enforces sound null safety,
making it impossible to unintentionally access a member on a null value.
In Dart, types are non-nullable by default. Variables of non-nullable types must be initialized and can only be assigned non-null values.
The Dart analyzer and compilers catch unsafe usage
of potentially null values at edit time,
turning what would be runtime errors in other languages
into analysis errors you can fix before deploying.
Examples
#None of the variables in the following code can be null:
// None of these can ever be null.
var i = 42; // Inferred to be an int.
String name = getFileName();
final b = Foo();
To indicate that a variable can have the value null,
add ? to its type declaration:
int? aNullableInt = null;
- For interactive examples, try the Dart cheatsheet.
- To learn more about null safety, check out Understanding null safety.
空安全原则
#Dart 的空安全基于以下两条核心原则:
默认不可空
除非你将变量显式声明为可空,否则它一定是非空的类型。我们在研究后发现,非空是目前的 API 中最常见的选择,所以选择了非空作为默认值。
完全可靠
如果类型系统推断出某个变量或表达式具有不可空的类型,那么可以保证它在运行时永远不会为 null。
综合来看,这些原则带来了更少的错误、更精简的体积以及更快的运行速度。
以往的迁移资源
#
自 2023 年 5 月发布的 Dart 3 起,
Dart 已全面支持严格的空安全机制。如果你仍然需要将你的应用或者 package 迁移至空安全,请查阅 dart-community/migrate-to-null-safety
仓库中的文档。