Flutter物理平台检测插件physical_platform的使用

Flutter物理平台检测插件physical_platform的使用

欢迎使用 physical_platform,这是一个提供实用物理平台工具的包。

注意:如果你也在使用 virtual_platform,你可以选择只使用 omni_platformomni_platform 集成了 virtual_platformphysical_platform,不添加任何额外的功能。这样你只需要在 pubspec.yaml 中声明一个包。

警告:尽可能优先使用 virtual_platformdesign_language

为了提高可测试性,我的建议是首先依赖于:

  • 虚拟平台匹配器/调度器

    • 如果设计语言在运行时不会改变(通常意味着只使用一种设计语言),可以查阅 virtual_platform 包获取更多信息。
  • 设计语言匹配器/调度器

    • 如果设计语言在运行时会改变,可以查阅 design_language 包获取更多信息。

然而,在某些情况下,上述包无法使用;这时这个包就变得非常有用。

开始使用

你需要将 physical_platform 添加到你的依赖项中。

dependencies:
  physical_platform: ^latest # 替换为版本号

接下来,你需要导入 package:physical_platform/physical_platform.dart

使用方法

很多代码部分只依赖于物理平台。此包提供了基于表达式的、实用的物理平台工具,允许开发者编写比典型Dart代码更声明性的代码(见下面的例子)。它与 virtual_platform 的语法类似。

所有工具的参数都是函数,即 PhysicalPlatformDispatchermatchPhysicalPlatform 分别是类型 Widget Function(BuildContext context, Widget? child)T Function()。如果目标只是选择一个widget或值——需要传递函数表达式,例如 (ctx, _) => Text('text')() => 'value'

平台和平台组总结见 本README的结尾

PhysicalPlatformDispatcher

这个调度器依赖于物理平台。

它构建一个widget,用于在不支持所有平台的情况下使用。例如,截至2022年,flutter_webview 插件还不支持桌面操作系统:

PhysicalPlatformDispatcher(
  android: (_, __) => MyWebView(),
  ios: (_, __) => MyWebView(),
  other: (_, __) => Center(child: Text('platform not supported')),
);

或者也可以这样:

PhysicalPlatformDispatcher(
  mobileSystems: (_, __) => MyWebView(),
  other: (_, __) => Center(child: Text('platform not supported')),
);

平台和平台组总结见 本README的结尾

上下文和子组件提供

有时可能需要上下文。所有构建器的第一个参数是一个 BuildContext context。你还可以指定一个 Widget? child 组件,这样你就无需在所有构建器中重复它。

示例:

return MaterialApp(
    title: 'Flutter Demo',
    theme: ThemeData(
        primarySwatch: Colors.blue,
    ),
    home: Scaffold(
        appBar: AppBar(title: const Text('example')),
        body: PhysicalPlatformDispatcher(
            child: const CommonSubtree(),
            mobileSystems: (context, child) => SpecialWidget(
                child,
                onPressed(() { /* do something with context */ }),
            ),
            other: (context, child) => OtherSpecialWidget(
                child,
                onPressed(() { /* do something with context */ }),
            ),
        ),
    ),
);

matchPhysicalPlatform

matchPhysicalPlatform 是一种声明模式,用于为匹配的物理平台调用正确的函数。它使用泛型。

使用示例:

// 你应该在这里使用path_provider来正确处理
final dbPath = matchPhysicalPlatform(
  other: () => 'default/path/to/db',
  android: () => 'path/to/db/on/android',
  macos: () => 'path/to/db/on/macOS',
);

dbPath 将在所有平台上(包括web)具有值 default/path/to/db,除了Android和macOS。

这个函数可能是你从 physical_platform 包中最常用的工具。

这种解决方案比典型的Dart代码更实用的原因是什么?

示例 1

这个包:

matchPhysicalPlatform(
    mobileSystems: () {...},
    desktopSystems: () {...},
    web: () {...},
    other: () {...},
);

典型的Dart:

if (kIsWeb) { // 这应该总是放在最前面
    ...
} else if (Platform.isIOS || Platform.isAndroid) {
    ...
} else if (Platform.isLinux || Platform.isWindows || Platform.isMacOS) {
    ...
} else {
    ...
}

示例 2

这个包:

matchPhysicalPlatform(
    android: () {...},
    ios: () {...},
    web: () {...},
    other: () {...},
);

典型的Dart:

if (kIsWeb) {
    ...
} else if (Platform.isIOS) {
    ...
} else if (Platform.isAndroid) {
    ...
} else {
    ...
}

平台和平台组


平台 appleSystems mobileSystems desktopSystems
android
ios
linux
macOS
windows
web
fuchsia

优先顺序:从左到右。

完整示例

以下是一个完整的示例,展示了如何在项目中使用 physical_platform

import 'package:flutter/material.dart';
import 'package:physical_platform/physical_platform.dart';
import 'package:webview_flutter/webview_flutter.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(title: const Text('example')),
        body: Builder(builder: (context) {
          return PhysicalPlatformDispatcher(
            mobileSystems: (_, __) =>
                const WebView(initialUrl: "https://wikipedia.org"),
            other: (_, __) => Center(
              child: Text(
                  'Platform doesn\'t support the official webview\n${context.size}'),
            ),
          );
        }),
      ),
    );
  }

  Widget a() {
    return ElevatedButton(
      onPressed: () {
        // do smth with context
      },
      child: const Text('mobile'),
    );
  }
}

更多关于Flutter物理平台检测插件physical_platform的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter物理平台检测插件physical_platform的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,下面是一个关于如何使用 physical_platform 插件在 Flutter 中检测物理平台(如 Android、iOS、Windows、macOS、Linux 等)的代码示例。physical_platform 插件允许你获取当前运行 Flutter 应用的平台信息。

首先,你需要在你的 pubspec.yaml 文件中添加 physical_platform 依赖:

dependencies:
  flutter:
    sdk: flutter
  physical_platform: ^0.x.x  # 请替换为最新版本号

然后运行 flutter pub get 来获取依赖。

接下来,你可以在你的 Dart 代码中使用 physical_platform 来检测当前平台。以下是一个简单的示例:

import 'package:flutter/material.dart';
import 'package:physical_platform/physical_platform.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Physical Platform Detection'),
        ),
        body: Center(
          child: PlatformDetectionWidget(),
        ),
      ),
    );
  }
}

class PlatformDetectionWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return FutureBuilder<PhysicalPlatform>(
      future: PhysicalPlatform.instance,
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.done) {
          final platform = snapshot.data!;
          return Text(
            'Current Platform: ${describeEnum(platform.operatingSystem)} (${platform.runtimeOS})\n'
            'Is Android: ${platform.isAndroid}\n'
            'Is iOS: ${platform.isIOS}\n'
            'Is Windows: ${platform.isWindows}\n'
            'Is macOS: ${platform.isMacOS}\n'
            'Is Linux: ${platform.isLinux}\n'
            'Is Fuchsia: ${platform.isFuchsia}\n'
            'Is Web: ${platform.isWeb}',
            style: TextStyle(fontSize: 18),
            textAlign: TextAlign.center,
          );
        } else {
          return CircularProgressIndicator();
        }
      },
    );
  }
}

在这个示例中,我们做了以下几件事:

  1. pubspec.yaml 文件中添加了 physical_platform 依赖。
  2. 创建了一个简单的 Flutter 应用,其中包含一个 PlatformDetectionWidget 小部件。
  3. 使用 FutureBuilder 来异步获取 PhysicalPlatform 实例。
  4. 使用获取到的 PhysicalPlatform 实例来检测当前平台,并显示相关信息。

describeEnum 函数用于将枚举值转换为字符串,这在处理 PhysicalPlatform.OperatingSystem 枚举时特别有用。你可能需要在你的代码中定义这个函数,或者简单地使用 platform.operatingSystem.toString() 替换 describeEnum(platform.operatingSystem)

注意:physical_platform 插件的 API 可能会随着版本的更新而发生变化,因此请务必查阅最新的文档和示例代码以确保兼容性。

回到顶部