gpt4 book ai didi

Flutter - 如何为平台(Android、iOS、Web)使用条件编译?

转载 作者:行者123 更新时间:2023-12-03 03:22:30 24 4
gpt4 key购买 nike

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

我看到了几种解决方案:

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

    还有条件编译支持的问题。我找到了这个 article并且条件编译非常有限。
  • 创建您自己的插件并充分使用它。但它更加劳动密集。

    你有什么建议也许有第三种方式?
  • 最佳答案

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

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

    - 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
    这是在编译时( stub )实际解决的问题 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 上找到一篇很好的文章来解释这一点。 .

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

    关于Flutter - 如何为平台(Android、iOS、Web)使用条件编译?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61677387/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com