Try the following:
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(); }
To use your example above:
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</"; }); }
And used like this:
loadImports("<div import='myfragment.txt'></div>").then(print);
or, if used in async function:
print(await loadImports("<div import='myfragment.txt'></div>"));
Tonio source share