我正在使用archive包来扩展zip文件,如下所示:
final bytes = new File(zippedFile).readAsBytesSync();
final archive = new ZipDecoder().decodeBytes(bytes);
for (var file in archive) {
final filename = '/Users/mark/blah/${file.name}';
if (file.isFile) {
var outFile = new File(filename);
outFile = await outFile.create(recursive: true);
await outFile.writeAsBytes(file.content);
} else {
await new Directory(filename)
.create(recursive: true);
}
}
问题是我的Flutter中的UI线程不时挂起,这导致CircularProgressIndicator停顿了-我怀疑问题是对file.content的调用。如何在不阻塞UI线程的情况下调用它?我需要使用隔离器吗?
答案 0 :(得分:1)
如果使用Flutter,这是基于GünterZöchbauer的评论的一种解决方案:
final bytes = new File(zippedFile).readAsBytesSync();
final archive = new ZipDecoder().decodeBytes(bytes);
for (var file in archive) {
final filename = '/Users/mark/blah/${file.name}';
if (file.isFile) {
final decompressed = await compute(decompressArchiveFile, file);
var outFile = new File(filename);
outFile = await outFile.create(recursive: true);
await outFile.writeAsBytes(decompressed);
} else {
await new Directory(filename)
.create(recursive: true);
}
}
这是decompressArchiveFile
函数:
List<int> decompressArchiveFile(ArchiveFile file) {
return file.content;
}
此方法有效,但速度是sync方法的5倍。