【发布时间】:2021-10-09 20:14:27
【问题描述】:
我注意到一旦选择了一个大文件,我的应用就会冻结。所以我想出了一个想法,让字节在隔离线程中生成。完成生成后,让它显示在Image 小部件中。
第一个选择的文件将被添加到 urlImageSink 中。
@override
Future<String>userImage(File images) async {
if (images.path.contains(".pdf")) {
urlListImages.add(images.path);
_bloc.urlImageSink.add(urlListImages);
}
}
接下来它将运行StreamBuilder,在FutureBuilder中调用loadPdfFirstPage。
Widget _showAttachFile() {
return Padding(
padding: EdgeInsets.all(10),
child: StreamBuilder<List<dynamic>>(
stream: _bloc.urlImageStream,
builder: (context, snapshot) {
if (snapshot.hasData) {
return GridView.builder(
shrinkWrap: true,
physics: NeverScrollableScrollPhysics(),
gridDelegate: new SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3,
mainAxisSpacing: 5.0,
crossAxisSpacing: 5.0,
),
itemCount: snapshot.data.length + 1,
itemBuilder: (BuildContext context, int index) => new Padding(
padding: const EdgeInsets.all(5.0),
child: Container(
padding: EdgeInsets.zero,
height: 150,
width: 150,
child: FutureBuilder<Uint8List>(
future:
loadPdfFirstPage(File(snapshot.data[index])),
builder: (context, snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.done:
if (snapshot.hasData) {
return Image(
image: MemoryImage(snapshot.data));
);
} else {
return Text("Null");
}
break;
case ConnectionState.waiting:
return CircularProgressIndicator();
break;
default:
return Text("Error");
}
},
),
),
));
} else {
return Text("No Data");
}
}),
);
}
在 loadPdfFirstPage 方法中,我运行了 compute 方法来生成字节。
Future<Uint8List> loadPdfFirstPage(File pdfFile) =>
compute(generateBytes, pdfFile);
Future<Uint8List> generateBytes(File pdfFile) async {
final document = await PdfDocument.openFile(pdfFile.path);
final page = await document.getPage(1);
final pageImage = await page.render(width: page.width, height: page.height);
await page.close();
return pageImage.bytes;
}
每次选择文件时,我都会立即从FutureBuildersnapshot.data 获取输出Null。 loadPdfFirstPage 好像没有打电话。
我在这里做错了什么?
【问题讨论】:
-
generateBytes 是在哪里定义的?
-
@LayneBernardo 在计算函数中。
-
Isolates communicate by passing messages back and forth. These messages can be primitive values, such as null, num, bool, double, or String, or simple objects such as the List<Photo> in this example.所以我觉得File不简单 -
@Nagual 但如果我想选择一个大文件怎么办?
-
我没有检查,但尝试将其 base64 编码为字符串并改为传递 Uint8List,与文件相同 - 尝试不传递文件,而仅传递路径(字符串)
标签: flutter dart stream-builder flutter-futurebuilder isolation