[英]Conditional imports / code for Dart packages
有什么方法可以根据环境标志或Dart中的目标平台有条件地导入库/代码吗? 我试图在dart:io
的ZLibDecoder / ZLibEncoder类和基于目标平台的zlib.js之间切换。
有一篇文章描述了如何创建一个统一的界面 ,但是我无法形象化这种技术,即不创建重复的代码,也不进行冗余测试以测试该重复的代码。 game_loop
采用了这种技术 ,但是使用了似乎不共享任何东西的单独类(GameLoopHtml和GameLoopIsolate)。
我的代码看起来像这样:
class Parser {
Layer parse(String data) {
List<int> rawBytes = /* ... */;
/* stuff you don't care about */
return new Layer(_inflateBytes(rawBytes));
}
String _inflateBytes(List<int> bytes) {
// Uses ZLibEncoder on dartvm, zlib.js in browser
}
}
我想通过具有两个单独的类(ParserHtml和ParserServer)来避免代码重复,除了_inflateBytes
之外, _inflateBytes
都实现相同的所有_inflateBytes
。
编辑:此处的具体示例: https : //github.com/radicaled/citadel/blob/master/lib/tilemap/parser.dart 。 这是一个TMX(磁贴图XML)解析器。
您可以使用镜子(反射)解决此问题。 pub包路径正在使用反射来访问独立VM上的dart:io
或浏览器中的dart:html
。
源位于此处 。 好消息是,它们使用@MirrorsUsed
,因此仅将所需的类包含在mirrors api中。 我认为该代码已被很好地记录下来,应该很容易为您的代码采用该解决方案。
从吸气器_io
和_html
(在第72行声明)开始,它们表明您可以加载库,而在您的VM类型上不可用。 如果库不可用,则加载只会返回false。
/// If we're running in the server-side Dart VM, this will return a
/// [LibraryMirror] that gives access to the `dart:io` library.
///
/// If `dart:io` is not available, this returns null.
LibraryMirror get _io => currentMirrorSystem().libraries[Uri.parse('dart:io')];
// TODO(nweiz): when issue 6490 or 6943 are fixed, make this work under dart2js.
/// If we're running in Dartium, this will return a [LibraryMirror] that gives
/// access to the `dart:html` library.
///
/// If `dart:html` is not available, this returns null.
LibraryMirror get _html =>
currentMirrorSystem().libraries[Uri.parse('dart:html')];
稍后,您可以使用镜像来调用方法或获取方法。 有关示例实现,请参见吸气剂current
(从第86行开始)。
/// Gets the path to the current working directory.
///
/// In the browser, this means the current URL. When using dart2js, this
/// currently returns `.` due to technical constraints. In the future, it will
/// return the current URL.
String get current {
if (_io != null) {
return _io.classes[#Directory].getField(#current).reflectee.path;
} else if (_html != null) {
return _html.getField(#window).reflectee.location.href;
} else {
return '.';
}
}
正如您在评论中看到的那样,目前这仅适用于Dart VM。 解决问题6490后,它也应在Dart2Js中工作。 这可能意味着此解决方案暂时不适合您,但以后将成为解决方案。
问题6943可能也有帮助,但描述了另一个尚未实现的解决方案。
基于dart:html
或dart:io
的存在,有条件的导入是可能的,例如,参见package:resource中resource_loader.dart的import语句。
我尚不确定如何在Flutter平台上进行导入。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.