為 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.flutter.club.tw/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