Flutter 合并 ‘dot-shorthands‘ 语法糖,Dart 开始支持交叉编译
最近在 Dart 在 main 3.9 合并了一项名为 「dot-shorthands」 的语法糖提议,该提议主要是为了简化开发过程中的相关静态固定常量的写法,通过上下文类型推断简化枚举值和静态成员的访问:
简单来说,就是在之前你可能需要写 SomeEnum.someValue
,而在此之后,你只需要写 .someValue
,简写语法不仅限于枚举值,还可用于访问静态 getter、构造函数和函数等:
///之前
SomeEnum getValue() => SomeEnum.someValue;///之后
SomeEnum getValue() => .someValue;
如果回到 Flutter 场景下,那就是如下代码所示,不管是各类 Flex
控件的 Axis
,还是类似 Offset
等的 Zero
,以后都可以通过如 .zero
、.center
来实现简化写法:
如下图所示,通过上下文推断,最终 center 可以被正常识别并打印:
当然,既然说了是类型推断,那么 dynamic 肯定是不行,比如此时的 test
根本无法推断出其类型:
当然,如果在初始化时赋值,那么 test 的类型就可以被推断并确认:
不过如果你强行指定了 dynamic
类型肯定还是不行的:
另外,在内置的 Color
和 Colors
场景也不适用,这类场景下,因为它们的静态类型和本身的类型并不是同一个,所以也会出现无法简化的情况:
而根据 ‘dot-shorthands’ 的语法糖效果,大致常用的简化支持可以如下代码所示:
void main() {print(getterArrow); print(getterBody); print(Methods().getterArrow); print(Methods().getterBody); print(Methods.getterArrowStatic); print(Methods.getterBodyStatic);
}enum Color { red, blue, green }Color get getterArrow => .red;
Color get getterBody { return .red; }class Methods {static Color get getterArrowStatic => .red;static Color get getterBodyStatic { return .red; }Color get getterArrow => .red;Color get getterBody { return .red; }
}
因为目前该语法糖仅在 main 分支可用,需要 Dart 3.9 下在运行时执行 flutter run --enable-experiment=dot-shorthands
才能运行:
可以看到这是一个非常简单的语法糖,整体来说对于开发简化还是挺不错的,那么你会喜欢这个写法吗?
最后, 在 Flutter main channel 中还提供了一个新功能:支持交叉编译 Dart AOT 可执行文件,目前支持从 Windows 和 macOS 编译为 Linux 二进制文件:
--target-os=linux
--target-arch=value
:目标体系结构,可以是arm64
(64 位 ARM 处理器)或x64
(64 位处理器)
例如 :
dart compile exe --target-os=linux --target-arch=x64 hello.dart -o hello
目前,执行这个命令会下载额外的 Dart SDK 二进制文件,并将它们缓存在 ~/.dart
目录 :
Downloading https://storage.googleapis.com/dart-archive/channels/dev/signed/hash/...4864.../sdk/gen_snapshot_macos_arm64_linux_x64...
Downloading https://storage.googleapis.com/dart-archive/channels/dev/raw/hash/...64e44.../sdk/dartaotruntime_linux_x64...
Specializing Platform getters for target OS linux.
Generating AOT kernel dill.
Compiling /tmp/hello.dart to /tmp/hello.exe using format Kind.exe:
Generating AOT snapshot. path/to/dir/.dart/3.8.0-265.0.dev/gen_snapshot_macos_arm64_linux_x64 []
Generating executable.
Marking binary executable.
Generated: /tmp/hello.exe
例如在 window 上通过 dart compile exe --target-os=linux hello.dart -o hello
编译下方代码,然后到 linux 下执行,可以看到代码可以正常运行:
void main() {for (var i = 0; i < 10; i++) {print('hello ${i + 1}');}
}
那么,你觉得 Dart 上的交叉编译是否会是刚需?
结合之前的 Dart 3.8 开始支持 Null-Aware Elements 语法,感觉 Dart 在近期语法糖调整还是挺多的,就是大家更关心的 build_runner 优化和序列化改进何时才能见到。