You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter使用screenshot与pdf插件生成PDF时PdfImage无法赋值给ImageProvider求助

错误原因

  1. 你引入的pdf(代码中别名为pw)包在较新版本中,pw.Image组件要求传入的参数为ImageProvider类型,你直接传入PdfImage实例不符合类型要求。
  2. 你调用getPdf方法的时机错误:screenshotController.capture()是异步方法,你在then回调外直接调用getPdf(_imageFile)时,_imageFile还未被赋值,会传入空值导致后续异常。

修复方案

1. 调整PDF生成代码

直接使用pw.MemoryImage包裹截图的Uint8List数据即可,不需要手动构建PdfImage实例,修复后的代码如下:

Future getPdf(Uint8List screenShot) async {
    pw.Document pdf = pw.Document();
    pdf.addPage(
      pw.Page(
        pageFormat: PdfPageFormat.a4,
        build: (context) {
          return pw.Expanded(
              child: pw.Image(pw.MemoryImage(screenShot), fit: pw.BoxFit.contain)
          );
        },
      ),
    );
    File pdfFile = File('你的自定义存储路径/生成的文件名.pdf');
    pdfFile.writeAsBytesSync(await pdf.save());
  }

2. 调整截图后调用PDF生成的逻辑

将getPdf调用放到capture的成功回调内,等截图数据返回后再执行PDF生成操作,修复后的代码如下:

Uint8List? _imageFile;
screenshotController.capture().then((Uint8List? image) {
  if(image == null) return;
  // 截图完成
  setState(() {
    _imageFile = image;
  });
  // 拿到截图数据后再生成PDF
  getPdf(image);
}).catchError((onError) {
  print(onError);
});

注意事项

如果需要将PDF存储到设备公共存储目录,需要提前申请对应平台的存储读写权限,并配置好权限声明。

内容的提问来源于stack exchange,提问作者Ananthakrishna

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 14:42:04