【发布时间】:2020-12-05 05:03:57
【问题描述】:
我想在 PC 和移动设备上使用不同的应用程序,那么在加载应用程序之前找出设备是什么的最佳方法是什么?
【问题讨论】:
标签: flutter dart flutter-web
我想在 PC 和移动设备上使用不同的应用程序,那么在加载应用程序之前找出设备是什么的最佳方法是什么?
【问题讨论】:
标签: flutter dart flutter-web
由于网络不支持dart:io,另一种解决方案是查看用户代理(警告:用户可能会伪造它以加载移动或桌面版本)。
import 'package:universal_html/html.dart' as html;
const appleType = "apple";
const androidType = "android";
const desktopType = "desktop";
String getSmartPhoneOrTablet() {
final userAgent = html.window.navigator.userAgent.toString().toLowerCase();
// smartphone
if( userAgent.contains("iphone")) return appleType;
if( userAgent.contains("android")) return androidType;
// tablet
if( userAgent.contains("ipad")) return appleType;
if( html.window.navigator.platform.toLowerCase().contains("macintel") && html.window.navigator.maxTouchPoints > 0 ) return appleType;
return desktopType;
}
归功于: https://github.com/flutter/flutter/issues/41311#issuecomment-739854345
【讨论】:
您可以使用dart:io 的Platform class 来执行此操作,它提供了一些静态属性,可以帮助您确定操作系统,从而确定PC 与移动设备。
以下返回bools 可帮助您确定每个操作系统
isAndroid,
isFuchsia,
isIOS,
isLinux,
isMacOS,
isWindows
或者您可以使用operatingSystem 属性,它返回包含操作系统的String。
例如
if(Platform.isWindows)
...
一般来说,如果您将 Android 和 iOS 视为操作系统,您就会知道它是移动的。如果您看到 Linux、MacOS 或 Windows,您就会知道它是 PC。而且Fuchsia有点暧昧。
【讨论】:
Unsupported operation: Platform._operatingSystem
dart:io。你应该得到一个关于这个的 linter 警告。如果您想在网络上查找此信息,则需要使用单独的包或自己制作。
kIsWeb:如果应用程序被编译为在 Web 上运行,则该常量为真。
import 'package:flutter/foundation.dart';
if(!kIsWeb) {
// Use for mobile
} else{
//use for web
}
【讨论】: