【问题标题】:How to ascertain whether the Flutter web app is running on phone or PC?如何确定 Flutter Web 应用是在手机还是 PC 上运行?
【发布时间】:2020-12-05 05:03:57
【问题描述】:

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

【问题讨论】:

标签: flutter dart flutter-web


【解决方案1】:

由于网络不支持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

【讨论】:

    【解决方案2】:

    您可以使用dart:ioPlatform 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
    • @DanielS。您不能在 Web 库中使用 dart:io。你应该得到一个关于这个的 linter 警告。如果您想在网络上查找此信息,则需要使用单独的包或自己制作。
    【解决方案3】:

    kIsWeb:如果应用程序被编译为在 Web 上运行,则该常量为真。

    import 'package:flutter/foundation.dart';
    if(!kIsWeb) {
        // Use for mobile
    } else{
    //use for web
    } 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-06
      • 2010-10-23
      • 2013-02-27
      • 1970-01-01
      • 2023-01-21
      • 2013-08-31
      • 1970-01-01
      • 2020-02-24
      相关资源
      最近更新 更多