如何确定 Flutter Web 应用程序是在手机上还是在 PC 上运行?

Sha*_*hav 3 dart flutter flutter-web

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

Gpa*_*ack 7

由于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;
}
Run Code Online (Sandbox Code Playgroud)

归功于:https : //github.com/flutter/flutter/issues/41311#issuecomment-739854345


Chr*_*ore 0

You can do this with the Platform class of of dart:io, which provides a few static properties that can help you determine the OS and therefore PC vs mobile.

The following return bools that help you determine each OS

isAndroid, isFuchsia, isIOS, isLinux, isMacOS, isWindows

或者您可以使用该operatingSystem属性,该属性返回String包含操作系统的属性。

前任。

if(Platform.isWindows)
...
Run Code Online (Sandbox Code Playgroud)

一般来说,如果您将 Android 和 iOS 视为操作系统,您就会知道它是移动的。如果您看到 Linux、MacOS 或 Windows,您就会知道它是 PC。而紫红色则有点暧昧。

  • 在网络上,这对我不起作用。我收到以下错误“不支持的操作:Platform._operatingSystem” (3认同)
  • @丹尼尔S。您不能在网络库中使用“dart:io”。您应该收到关于此的 linter 警告。如果您想在网络上查找此信息,则需要使用单独的包或自己制作。 (3认同)