[英]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.