如何确定 Flutter web 应用程序是 运行 在 phone 还是 PC 上?

How to ascertain whether the Flutter web app is running on phone or PC?

我想在 PC 和移动设备上使用不同的应用程序,那么在加载应用程序之前找出设备是什么的最佳方法是什么?

您可以使用 dart:ioPlatform class 来执行此操作,它提供了一些 static 属性,可以帮助您确定 OS 因此 PC 与移动设备。

以下 return bool 可帮助您确定每个 OS

isAndroid, isFuchsia, isIOS, isLinux, isMacOS, isWindows

或者您可以使用 operatingSystem 属性,其中 return 是包含 OS.

String

例如

if(Platform.isWindows)
...

一般来说,如果您看到 Android 和 iOS 作为 OS,您就会知道它是移动的。如果您看到 Linux、MacOS 或 Windows,您就会知道它是 PC。而Fuchsia有点模棱两可。

由于 dart:io 在 Web 上不受支持,另一种解决方案是查看用户代理(警告:用户可能会伪造它以加载移动或桌面版本)。

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

你可以用这个代码轻松找到

bool isMobile = MediaQuery.of(context).size.width < 850;
bool isTablet = MediaQuery.of(context).size.width < 1100 &&
    MediaQuery.of(context).size.width >= 850;
bool isDesktop = MediaQuery.of(context).size.width >= 1100;