【问题标题】:Flutter - How use conditional compilation for platform (Android, iOS, Web)?Flutter - 如何为平台(Android、iOS、Web)使用条件编译?
【发布时间】:2020-08-23 21:44:42
【问题描述】:

我正在 Flutter 中创建一个移动应用程序。现在我有一个问题,一个平台我会用一个插件另一个平台,我需要编写我的平台代码(插件的实现不适合)。

我看到了几种解决方案:

  1. 最好创建多个项目并在其中使用条件编译和共享文件。我在视觉工作室中使用了这种技术。但我现在正在使用 android studio。没有项目文件,只有文件夹。

    条件编译支持也有问题。我发现了这个article,条件编译非常有限。

  2. 创建您自己的插件并充分使用它。但它更劳动密集。

    你有什么建议,也许还有第三种方法?

【问题讨论】:

    标签: flutter dart conditional-statements flutter-dependencies


    【解决方案1】:

    在使用多个环境(例如 IO 和 Web)时,添加存根类以在编译时解决依赖关系可能很有用,这样,您可以轻松集成多个平台相关库,而不会影响每个库的编译。

    例如,可以有一个按以下方式构建的插件:

    - my_plugin_io.dart
    - my_plugin_web.dart
    - my_plugin_stub.dart
    - my_plugin.dart
    

    让我们用一个简单的例子来分解它:

    my_plugin.dart

    在这里,您实际上可以让您的插件类在多个项目(即环境)中使用。

    import 'my_plugin_stub.dart'
        if (dart.library.io) 'my_plugin_io.dart'
        if (dart.library.html) 'my_plugin_web.dart';
    
    class MyPlugin {
    
      void foo() {
         var bar = myPluginMethod(); // it will either resolve for the web or io implementation at compile time
      }
    }
    

    my_plugin_stub.dart

    这将在编译时实际解析(存根)到正确的myPluginMethod() 方法。

    Object myPluginMethod() {
      throw UnimplementedError('Unsupported');
    }
    

    然后创建平台实现

    my_plugin_web.dart

    import 'dart:html' as html;
    
    Object myPluginMethod() {
      // Something that use dart:html data for example
    }
    

    my_plugin_io.dart

    import 'dart:io';
    
    Object myPluginMethod() {
      // Something that use dart:io data for example
    }
    

    其他官方替代方案可能来自创建共享相同界面的独立项目。这就像 Flutter 团队一直在为他们的 web + io 插件所做的那样,从而产生一个可以与多个项目捆绑在一起的项目:

    - my_plugin_io
    - my_plugin_web
    - my_plugin_desktop
    - my_plugin_interface
    

    可以在here找到一篇很好的文章来解释这一点。

    刚刚在 SO 中输入了它,所以如果我有一些错字,我很抱歉,但你应该很容易在编辑器上找到它。

    【讨论】:

      【解决方案2】:

      你只需要导入:

      import 'dart:io';
      

      然后使用基于以下条件的条件:

      // Platform.isIOS       // Returns true on iOS devices
      // Platform.isAndroid   // Returns true on Android devices
      
      
      if (Platform.isIOS) {
        navigationBar = new BottomNavigationBar(...);
      }
      if (Platform.isAndroid) {
        drawer = new Drawer(...);
      }
      

      【讨论】:

      • 那将是运行时
      【解决方案3】:

      添加这个库(不需要包)

      import 'dart:io' show Platform;
      

      现在您可以创建一个函数来检查用户正在使用哪个平台。

      Widget getWidgetBasedOnPlatform() {
        if (Platform.isIOS) {
          return Container(); //the one for iOS
        }
        else if (Platform.isAndroid) {
          return Container(); //the one for Android 
        }
      }
      

      【讨论】:

        猜你喜欢
        • 2015-09-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-28
        • 2016-08-17
        • 1970-01-01
        • 1970-01-01
        • 2020-08-24
        相关资源
        最近更新 更多