Fet*_*mos 2 conditional-statements dart flutter flutter-dependencies
我正在 Flutter 中创建一个移动应用程序。现在我有一个问题,对于一个平台我将使用另一个平台的插件,我需要编写我的平台代码(插件的实现不合适)。
我看到了几种解决方案:
最好创建多个项目并在其中使用条件编译和共享文件。我在视觉工作室中使用了这种技术。但我现在正在使用 android studio。没有项目文件,只有文件夹。
还有条件编译支持的问题。我发现这篇文章和条件编译非常有限。
创建您自己的插件并充分使用它。但它更劳动密集。
你有什么建议也许有第三种方式?
当使用多个环境(例如 IO 和 Web)时,添加存根类以在编译时解析依赖项可能很有用,这样,您可以轻松集成多个平台相关库,而不会影响每个库的编译。
例如,一个插件可以按以下方式构建:
- my_plugin_io.dart
- my_plugin_web.dart
- my_plugin_stub.dart
- my_plugin.dart
Run Code Online (Sandbox Code Playgroud)
让我们分解一下,举一个简单的例子:
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
}
}
Run Code Online (Sandbox Code Playgroud)
my_plugin_stub.dart这将在编译时(存根)实际解决为正确的myPluginMethod()方法。
Object myPluginMethod() {
throw UnimplementedError('Unsupported');
}
Run Code Online (Sandbox Code Playgroud)
然后创建平台实现
my_plugin_web.dartimport 'dart:html' as html;
Object myPluginMethod() {
// Something that use dart:html data for example
}
Run Code Online (Sandbox Code Playgroud)
my_plugin_io.dartimport 'dart:io';
Object myPluginMethod() {
// Something that use dart:io data for example
}
Run Code Online (Sandbox Code Playgroud)
其他官方替代方案可以通过创建共享相同界面的分离项目来传递。这就像 Flutter 团队一直在为他们的 web + io 插件做的那样,导致一个项目可以捆绑多个项目:
- my_plugin_io
- my_plugin_web
- my_plugin_desktop
- my_plugin_interface
Run Code Online (Sandbox Code Playgroud)
可以在此处找到解释这一点的好文章。
刚刚在这里输入了它,所以如果我有一些错字,我很抱歉,但你应该很容易在编辑器上找到它。
| 归档时间: |
|
| 查看次数: |
1604 次 |
| 最近记录: |