将 'linux' 和 'windows' 添加到 TargetPlatform 枚举
概述
#已向 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.fluttercn.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
情况的 switch 语句发出 missing_enum_constant_in_switch
警告。编写不带 default:
情况的 switch 语句是处理枚举的推荐方式,因为这样分析器可以帮助您找到任何未处理的情况。
迁移指南
#为了迁移到新的枚举并避免分析器的 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:
情况,因为这样分析器无法帮助您找到所有需要处理的情况。
此外,对于 Linux 和 Windows 应用程序,上述设置 debugDefaultTargetPlatformOverride
的任何测试都不再需要。
时间线
#引入版本: 1.15.4
稳定版本: 1.17
参考资料
#API 文档
相关问题
相关 PR