Flutter - flutter-web 中的条件库导入 [英] Flutter - Conditional library import in flutter-web
问题描述
假设 audioplayers|lib/audio_cache.dart
仅适用于 Android/iOS,我有条件地排除以下从 Dart 文件导入:
Supposing that audioplayers|lib/audio_cache.dart
worked only on Android/iOS, I conditionally exclude the following import from a Dart file:
import "package:audioplayers/audio_cache.dart"
通过以下方式:
import "dart:math" if (dart.library.io) "package:audioplayers/audio_cache.dart";
其中dart:math"可以是任何 fake_stub Dart 文件.简而言之,这在 Flutter 中导入仅适用于移动设备的库.详情此处(感谢Alois Deniel!).
where "dart:math" can be any fake_stub Dart file. In short this imports a library only for mobile devices in Flutter. Details here (thanks Alois Deniel!).
在 Flutter-Web 实现中隐藏平台特定代码的最佳方法是什么?
What would be the best way to hide platform-specific code in Flutter-Web implementation?
import 'dart:io' show Platform;
bool isMobile() => Platform.isAndroid || Platform.isIOS;
class _MyPageState extends State<MyPage> {
dynamic _audioPlayer;
@override
void initState() {
if (isMobile()) {
_audioPlayer = AudioCache(prefix: 'sounds/');
_audioPlayer.load('mysound.mp3');
}
}
}
当然,这个天真的尝试在 AudioCache
参考上失败了.
This naive try fails on AudioCache
reference of course.
Error: Method not found: 'AudioCache'.
_audioPlayer = AudioCache(prefix: 'sounds/');
推荐答案
In this stack overflow 问题 与您的要求相似,我根据 http 包.
In this stack overflow question which has similar requirements as yours, I wrote an answer based on this implementation from http package.
我认为您也可以使用类似的方法来处理这种条件依赖关系.我在那里提供了一个工作示例.我在这里引用答案.
I think you can also use a similar approach to handle this conditional dependencies. I have provided a working example there. I am quoting the answer here.
核心思想如下.
- 创建一个抽象类来定义您需要在一般情况下使用的方法.
- 创建扩展此抽象类的特定于
web
和android
依赖项的实现. - 创建一个存根,它公开一个方法来返回这个抽象实现的实例.这只是为了让 dart 分析工具满意.
- 在抽象类中导入此存根文件以及特定于
mobile
和web
的条件导入.然后在其工厂构造函数中返回具体实现的实例.如果写入正确,这将通过条件导入自动处理.
- Create an abstract class to define the methods you will need to use in genral.
- Create implementations specific to
web
andandroid
dependencies which extends this abstract class. - Create a stub which exposes a method to return the instance of this abstract implementation. This is only to keep the dart analysis tool happy.
- In the abstract class import this stub file along with the conditional imports specific for
mobile
andweb
. Then in its factory constructor return the instance of the specific implementation. This will be handled automatically by conditional import if written correctly.
这篇关于Flutter - flutter-web 中的条件库导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!