gpt4 book ai didi

dart - Dart Transformer无法覆盖 Assets

转载 作者:行者123 更新时间:2023-12-03 02:57:12 24 4
gpt4 key购买 nike

我写了一个AggregateTransformer,应该用更新的版本覆盖main.dart文件(更改导入)。

Asset mainAsset = await _getFileAsset(transform, "main.dart");
Asset updatedMainAsset = await _replaceDefaultImport(mainAsset, transform.package, "default.dart", newLibFileName);

//overwrite mainAsset because mainAsset and updatedMainAsset have the same id
transform.addOutput(updatedMainAsset);

(在添加新版本之前先删除 Assets 不会更改任何内容:)
transform.consumePrimary(mainAsset.id);
transform.addOutput(updatedMainAsset);

但是更新的版本消失得无影无踪。尝试通过id检索它会产生原始内容:
Asset updatedMainAssetRetrieved = await transform.getInput(updatedMainAsset.id);

转换器输出mainAsset和updatedMainAsset的内容,因此您可以检查updatedMainAsset的内容确实已更新。通过调用 pub run main.dart 来调用转换器。

完整的代码/伪代码如下所示:
class ReplacePackageTransformer extends AggregateTransformer {
ReplacePackageTransformer.asPlugin();

@override
String classifyPrimary(AssetId id) => id.toString().endsWith(".dart") ? "dart-files" : null;

@override
apply(AggregateTransform transform) {
//capture the whole execution to allow better stacktraces if an error occurs
Chain.capture(() async {
//create a file lib/replacement.dart that defines the same method as lib/default.dart
final newLibFileName = "replacement.dart";
final newLibAsset = _createReplacementAsset(...);
//add this new asset
transform.addOutput(newLibAsset);

//rewrite main.dart to import replacement.dart instead of default.dart. To that end:
//1) retrieve the asset for main.dart
Asset mainAsset = await _getFileAsset(transform, "main.dart");
//2) create a new asset with the same id as mainAsset but with updated content
Asset updatedMainAsset = await _replaceDefaultImport(mainAsset, ...);
//3) adding this asset should overwrite/replace the original main.dart-asset because they use the same id
transform.addOutput(updatedMainAsset);
});
}

//helper methods ...
}

您可以找到整个转换器(以及项目的其余部分) here

更新/解决方案

丹尼斯·卡斯洛(Dennis Kaselow)是对的!我的转换器的应用方法必须返回一个Future(以便后续的转换器可以等待它完成)!在对Chain.capture的调用之前添加返回就足够了(因为我捕获的回调具有异步主体,因此返回该捕获将转发/返回的Future)。

所以改变
apply(AggregateTransform transform) {
Chain.capture(() async {...});
//no return statement so void is returned
}


Future apply(AggregateTransform transform) {
return Chain.capture(() async {...});
//() async {...} returns a Future that Chain.capture and apply forward/return
}

解决了我的问题!

最佳答案

解决方案非常简单:只需在return前面添加Chain.capture即可。
apply的dartdoc说:

If this does asynchronous work, it should return a [Future] that completes once it's finished.



如果在转换后访问输入,则输入仍将是原始输入。您也不需要调用 transform.consumeInput

关于dart - Dart Transformer无法覆盖 Assets ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35398977/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com