Flutter-Flutter-Web中的条件库导入 [英] Flutter - Conditional library import in flutter-web
问题描述
假设 audioplayers | lib / audio_cache.dart
仅在Android / iOS上有效,我有条件地从文件中排除以下导入:
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/');
推荐答案
在此堆栈中问题,它与您的要求类似,我基于 http package。
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.
核心思想如下。
The core idea is as follows.
- 创建一个抽象类来定义一般需要使用的方法。
- 创建特定于
web
和<$ c $的实现c> android 依赖项扩展了这个抽象类。 - 创建一个存根,该存根公开一个方法来返回此抽象实现的实例。
- 在抽象类中,导入此存根文件以及特定于
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屋!