我正在开发一个需要模板的项目.主模板具有指定数据源的import属性.然后使用String.replaceAllMapped读取数据并将其插入到字符串中.以下代码适用于File api,因为它具有readAsStringSync方法来同步读取文件.我现在想要从任何返回Future的任意流中读取.
如何在这种情况下使async/await工作?我也找了一个异步兼容替换replaceAllMapped但我还没有找到一个不需要多次使用正则表达式的解决方案.
这是我的代码的一个非常简化的示例:
String loadImports(String content){
RegExp exp = new RegExp("import=[\"\']([^\"\']*)[\"\']>\\s*<\/");
return content.replaceAllMapped(exp, (match) {
String filePath = match.group(1);
File file = new File(filePath);
String fileContent = file.readAsStringSync();
return ">$fileContent</";
});
}
Run Code Online (Sandbox Code Playgroud)
用法示例:
print(loadImports("<div import='myfragment.txt'></div>"))
Run Code Online (Sandbox Code Playgroud)
尝试这个:
Future<String> replaceAllMappedAsync(String string, Pattern exp, Future<String> replace(Match match)) async {
StringBuffer replaced = new StringBuffer();
int currentIndex = 0;
for(Match match in exp.allMatches(string)) {
String prefix = match.input.substring(currentIndex, match.start);
currentIndex = match.end;
replaced
..write(prefix)
..write(await replace(match));
}
replaced.write(string.substring(currentIndex));
return replaced.toString();
}
Run Code Online (Sandbox Code Playgroud)
要使用上面的示例:
Future<String> loadImports(String content) async {
RegExp exp = new RegExp("import=[\"\']([^\"\']*)[\"\']>\\s*<\/");
return replaceAllMappedAsync(content, exp, (match) async {
String filePath = match.group(1);
File file = new File(filePath);
String fileContent = await file.readAsString();
return ">$fileContent</";
});
}
Run Code Online (Sandbox Code Playgroud)
并像这样使用:
loadImports("<div import='myfragment.txt'></div>").then(print);
Run Code Online (Sandbox Code Playgroud)
或者,如果在函数中使用async:
print(await loadImports("<div import='myfragment.txt'></div>"));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
162 次 |
| 最近记录: |