为 TargetPlatform 枚举添加 'linux' 和 'windows'
概述
#在 TargetPlatform
枚举中添加了两个新值,这可能会在切换 TargetPlatform
且不包含 default:
情况的 switch 语句中需要额外的 case。
背景
#在此更改之前,TargetPlatform
枚举只包含四个值,定义如下:
enum TargetPlatform {
android,
fuchsia,
iOS,
macOS,
}
switch
语句只需要处理这些情况,而想要在 Linux 或 Windows 上运行的桌面应用程序通常在其 main()
方法中有一个类似的测试:
// Sets a platform override for desktop to avoid exceptions. See
// https://docs.flutterdart.cn/desktop#target-platform-override for more info.
void _enablePlatformOverrideForDesktop() {
if (!kIsWeb && (Platform.isWindows || Platform.isLinux)) {
debugDefaultTargetPlatformOverride = TargetPlatform.fuchsia;
}
}
void main() {
_enablePlatformOverrideForDesktop();
runApp(MyApp());
}
变更说明
#现在 TargetPlatform
枚举定义如下:
enum TargetPlatform {
android,
fuchsia,
iOS,
linux, // new value
macOS,
windows, // new value
}
并且,在 Linux 和 Windows 上,main()
中用于设置平台测试的 debugDefaultTargetPlatformOverride
不再需要了。
这可能导致 Dart 分析器在没有 default
case 的 switch 语句中给出 missing_enum_constant_in_switch
警告。编写不带 default:
case 的 switch 是处理枚举的推荐方法,因为分析器可以帮助您找到所有未处理的 case。
迁移指南
#为了迁移到新枚举并避免分析器的 missing_enum_constant_in_switch
错误,该错误看起来像:
warning: Missing case clause for 'linux'. (missing_enum_constant_in_switch at [package] path/to/file.dart:111)
或
warning: Missing case clause for 'windows'. (missing_enum_constant_in_switch at [package] path/to/file.dart:111)
请按如下方式修改您的代码:
迁移前的代码
void dance(TargetPlatform platform) {
switch (platform) {
case TargetPlatform.android:
// Do Android dance.
break;
case TargetPlatform.fuchsia:
// Do Fuchsia dance.
break;
case TargetPlatform.iOS:
// Do iOS dance.
break;
case TargetPlatform.macOS:
// Do macOS dance.
break;
}
}
迁移后的代码
void dance(TargetPlatform platform) {
switch (platform) {
case TargetPlatform.android:
// Do Android dance.
break;
case TargetPlatform.fuchsia:
// Do Fuchsia dance.
break;
case TargetPlatform.iOS:
// Do iOS dance.
break;
case TargetPlatform.linux: // new case
// Do Linux dance.
break;
case TargetPlatform.macOS:
// Do macOS dance.
break;
case TargetPlatform.windows: // new case
// Do Windows dance.
break;
}
}
在这样的 switch 语句中包含 default:
case 是不推荐的,因为这样分析器就无法帮助您找到所有需要处理的 case。
此外,上面引用的用于设置 debugDefaultTargetPlatformOverride
的任何测试,对于 Linux 和 Windows 应用程序来说都不再需要了。
时间线
#引入版本: 1.15.4
稳定版本: 1.17
参考资料
#API 文档
相关问题
相关 PR