如何解决如何确定Flutter Web应用程序是在手机还是PC上运行?
我想在PC和移动设备上使用不同的应用程序,那么在加载应用程序之前找出设备的最佳方法是什么?
解决方法
由于网络不支持 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来做到这一点,它提供了一些 static 属性,可以帮助您确定操作系统以及PC与移动设备。
以下返回bool
可以帮助您确定每个操作系统
isAndroid
,
isFuchsia
,
isIOS
,
isLinux
,
isMacOS
,
isWindows
或者您可以使用operatingSystem
属性,该属性返回包含操作系统的String
。
例如。
if(Platform.isWindows)
...
通常,如果您将Android和iOS视为操作系统,则会知道它是可移动的。如果您看到Linux,MacOS或Windows,就会知道它是PC。紫红色有点模棱两可。
,kIsWeb:如果应用程序被编译为在网络上运行,则该常量为真。
import 'package:flutter/foundation.dart';
if(!kIsWeb) {
// Use for mobile
} else{
//use for web
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。