1. 问题
首先是一个bug,如果你在Web平台使用bool isIos = Platform.isIOS这样的代码,就会报错
Unsupported operation: Platform._operatingSystem
另一个问题就是并没有Platform.isWeb方法
2. 解决方法 universal_platform
库
🔨 安装
直接flutter pub add universal_platform
🕹️ 使用
老写法(Web会报错) | 新写法 |
---|---|
Platform.isIOS |
UniversalPlatform.isIOS |
Platform.isAndroid |
UniversalPlatform.isAndroid |
Platform.isWeb(不支持) |
UniversalPlatform.isWeb |
3. 鸿蒙来了,isOhos
呢?
现在大佬们也为Flutter适配了OpenHarmony,并且也提供了Platform.isOhos方法,但 universal_platform 是没有鸿蒙平台的判断的。
于是我直接fork了一下,把鸿蒙平台加了进去,也提了Pull Request。
feat: Add the ohos platform by qinshah · Pull Request #31 · gskinnerTeam/flutter-universal-platform
如果你也需要使用这个版本,可以在pubspec.yaml中进行修改
yaml
dependencies:
universal_platform:
git:
url: "https://github.com/qinshah/flutter-universal-platform.git"
4. 示例
dart
import 'package:flutter/material.dart';
import 'package:universal_platform/universal_platform.dart';
class PaltformJudgePage extends StatelessWidget {
const PaltformJudgePage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('平台判断')),
body: Center(
child: Text(
"Web: ${UniversalPlatform.isWeb} \n "
"MacOS: ${UniversalPlatform.isMacOS} \n"
"Windows: ${UniversalPlatform.isWindows} \n"
"OhOS: ${UniversalPlatform.isOhos} \n"
"Linux: ${UniversalPlatform.isLinux} \n"
"Android: ${UniversalPlatform.isAndroid} \n"
"IOS: ${UniversalPlatform.isIOS} \n"
"Fuschia: ${UniversalPlatform.isFuchsia} \n",
)),
);
}
}
平台 | 输出 |
---|---|
Chrome (Web) | Web: true |
Ohos | OhOS: true |

如果本文帮到你,欢迎去原仓库给 PR 点个 👍,一起让 Flutter和鸿蒙 生态更完整!