目录
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 (!)
1. 什么是sound null safety
从 Dart 2.12, Flutter 2.0开始支持这个特性
environment:
sdk: ">=2.12.0 <3.0.0"
使用这个特性之后发生变化如下:
- 默认变量的声明值都不能为 null, 即: non-nullable。
- 如果你想让这个变量可以为null, 在变量的数据类型声明后加 ? 表示该变量可以有值也可以为
- null, 即 nullable。
//下面的变量都不能为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;
2. Null safety的设计原则
-
Non-nullable by default 默认是 non-nullable: 如果没有指定变量为 nullable,默认即为 non-nullable。
-
Incrementally adoptable 逐步迁移: 在工程中可以同时存在空安全和非空安全混编的代码,并提供工具逐步迁移。
-
Fully sound 完全符合健壮性: 只要类型系统确定该变量是 non-nullable,即该变量永远都不会为 null, 并开启了编译器优化,拥有更小的二进制以及更快的运行速度。
3.相关操作符
-
Nullable and non-nullable types(?)
int ? a 申明?前面的类型可以为空类型
-
The null assertion operator (!)
int ? a;
int a = a!;
Point? point;
int b = point!.x;
告诉编译器express是非空的,可以赋值给一个非空的对象
-
late 关键字
用于当无法对 non-nullable 立即赋值的时候,可以用该关键字延迟赋值, 注意 late 关键字和 final 是可以共存的。以下三点
- 不需要立即赋值。
- 可以稍后赋值
- 在访问之前确保赋值了。(没赋值即访问抛异常
LateInitializationError
)
4. 旧的项目迁移到 null safety
- Wait for the packages that you depend on to migrate. 等待你依赖的库迁移完成
- Migrate your package’s code, preferably using the interactive migration tool. 迁移你的应用代码,使用交互性的迁移工具
- Statically analyze your package’s code. 分析你应用代码
- Test to make sure your changes work. 测试你的改变
- If the package is already on pub.dev, publish the null-safe version as a prerelease version. 如果你发布了包在远程仓库,发布null-safe的版本到正式仓库
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.执行改变