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

Flutter本地保存PDF时抛出FileSystemException无法打开文件异常

错误根因

报错是路径拼接非法导致的:getExternalStorageDirectory()返回值是Directory类型对象,你直接把这个对象赋值给path变量做字符串拼接时,会默认调用Directory类的toString()方法,最终拼出的路径是Directory: '/storage/emulated/0/Android/data/esofos.health/files'/test.pdf,这个路径格式完全不符合文件系统规范,自然无法打开文件写入。
另外你的文件写入操作没有加await,属于异步IO操作未等待执行完成就往下走,也可能触发资源释放相关的异常。

修复方案
  • 从Directory对象上取真实的路径字符串,不要直接用Directory对象做路径拼接
  • 对异步的文件写入方法加await等待执行完成,避免时序问题
  • 你当前使用的是应用专属外部存储目录,不需要额外申请存储权限,路径正确即可正常写入
修复后可运行代码
_generatepdf() async {
  // 获取外部存储目录
  final directory = await getExternalStorageDirectory();
  // 从Directory对象中取出实际路径字符串
  final path = directory?.path;
  // 目录为空时直接返回(兼容极端场景)
  if (path == null) return;
  // 创建PDF文档
  final PdfDocument document = PdfDocument();
  // 添加页面并绘制文本
  document.pages.add().graphics.drawString(
      'Hello World!', PdfStandardFont(PdfFontFamily.helvetica, 12),
      brush: PdfSolidBrush(PdfColor(0, 0, 0)),
      bounds: const Rect.fromLTWH(0, 0, 150, 20));

  // 等待写入完成
  final file = File('$path/test.pdf');
  await file.writeAsBytes(document.save());
  // 释放文档资源
  document.dispose();
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 11:18:08