目录
Non-nullable by default 默认是 non-nullable: 如果没有指定变量为 nullable,默认即为 non-nullable。
Incrementally adoptable 逐步迁移: 在工程中可以同时存在空安全和非空安全混编的代码,并提供工具逐步迁移。
Fully sound 完全符合健壮性: 只要类型系统确定该变量是 non-nullable,即该变量永远都不会为 null, 并开启了编译器优化,拥有更小的二进制以及更快的运行速度。
Nullable and non-nullable types(?)
The null assertion operator (!)
从 Dart 2.12, Flutter 2.0开始支持这个特性
environment:
sdk: ">=2.12.0 <3.0.0"
使用这个特性之后发生变化如下:
//下面的变量都不能为null In null-safe Dart, none of these can ever be null.
var i = 42; // Inferred to be an int.
String name = getFileName();
final b = Foo();
//在null-safe dart中表示该变量可以为null
int? aNullableInt = null;
int ? a 申明?前面的类型可以为空类型
int ? a;
int a = a!;
Point? point;
int b = point!.x;
告诉编译器express是非空的,可以赋值给一个非空的对象
用于当无法对 non-nullable 立即赋值的时候,可以用该关键字延迟赋值, 注意 late 关键字和 final 是可以共存的。以下三点
LateInitializationError
)https://dart.dev/null-safety/migration-guide 详细的引导在这个链接
//查看dart版本号码
dart --version
//检查当前依赖状态
dart pub outdated --mode=null-safety
//升级依赖
dart pub upgrade --null-safety
dart pub get
//通过工具迁移
dart migrate
通过迁移命令后,在浏览器会打开迁移结果,接下来需要做几件事情:
1. 理解迁移结果
2. 改进迁移结果 (看英文可能会更清楚一点)
In the Edit Details pane of the migration tool, you can insert hint markers using the Add /*?*/
hint and Add /*!*/
hint buttons.
These buttons add comments to your file immediately, and there’s no Undo. If you don’t want a hint that the tool inserted, you can use your usual code editor to remove it.
You can use an editor to add hint markers, even while the tool is still running. Because your code hasn’t opted into null safety yet, you can’t use new null-safety features. You can, however, make changes like refactoring that don’t depend on null-safety features.
When you’ve finished editing your code, click Rerun from sources to pick up your changes.
3.可以选择部分文件进行迁移
4.执行改变