將 'linux' 和 'windows' 加入 TargetPlatform 列舉
摘要
#TargetPlatform
列舉新增了兩個新值,這可能需要在 switch 語句中,針對 TargetPlatform
進行切換,且不包含 default:
情況時,增加額外的處理情況。
背景
#在此變更之前,TargetPlatform
列舉只包含四個值,並且定義如下
enum TargetPlatform {
android,
fuchsia,
iOS,
macOS,
}
switch
語句只需要處理這些情況,而想要在 Linux 或 Windows 上執行的桌面應用程式,通常會在它們的 main()
方法中進行如下的測試
// Sets a platform override for desktop to avoid exceptions. See
// https://flutter-docs.dev.org.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
情況的 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
除非另有說明,本網站的文件反映 Flutter 的最新穩定版本。頁面最後更新於 2024-04-04。 檢視原始碼 或 回報問題。