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

Flutter使用docx_template包添加图片时遇UnsupportedError错误求助

解决docx_template添加图片时的UnsupportedError错误

错误原因

从rootBundle.load获取的字节数组是不可修改的固定长度列表,而docx_template在生成文档的过程中需要对这个列表进行修改操作,从而触发了"Cannot modify an unmodifiable list"错误。

修复方案

将从rootBundle拿到的不可变字节数组转换为可修改的列表,再传入DocxTemplate.fromBytes。

关键代码修改

原代码片段:

var data = await rootBundle.load('assets/template.docx');
var bytes = data.buffer.asUint8List();
var docx = await DocxTemplate.fromBytes(bytes);

修改后:

var data = await rootBundle.load('assets/template.docx');
var bytes = data.buffer.asUint8List();
// 转换为可修改的列表
var mutableBytes = List<int>.from(bytes);
var docx = await DocxTemplate.fromBytes(mutableBytes);

完整修复后的代码

Future<File> storeImageInDocx(File imageFile) async {
  final appDocumentsDirectory = Platform.isAndroid
      ? await getExternalStorageDirectory() //FOR ANDROID
      : await getApplicationDocumentsDirectory();
  String fileDirectory = Platform.isAndroid
      ? "${appDocumentsDirectory?.path.split("Android")[0]}Download/iScanConnect"
      : "${appDocumentsDirectory?.path}";
  if (await Directory(fileDirectory).exists() != true) {
    Directory(fileDirectory).createSync(recursive: true);
  }
  String filePath =
      '$fileDirectory/${DateTime.now().millisecondsSinceEpoch}.docx';
  File file = File(filePath);
  var data = await rootBundle.load('assets/template.docx');
  var bytes = data.buffer.asUint8List();
  // 转换为可修改列表
  var mutableBytes = List<int>.from(bytes);
  var docx = await DocxTemplate.fromBytes(mutableBytes);

  var c = Content();
  c
    ..add(TextContent("docname", "Simple docname"))
    ..add(ImageContent("image", imageFile.readAsBytesSync()));
  List<int>? value = await docx.generate(c);
  if (value != null) {
    await file.writeAsBytes(value); // Write the generated .docx file to disk
    log('Docx saved to: $filePath');
    showCustomSnackBar(content: 'Docx saved to: $filePath');
    return file;
  } else {
    log('Error while saving Docx');
    showCustomSnackBar(content: 'Error while saving Docx');
    return File('');
  }
}

补充说明

Flutter的rootBundle加载资源时返回的字节缓冲区是只读的,docx_template在处理图片插入等模板替换操作时,需要修改原始模板的字节数据,因此必须将其转换为可修改列表才能正常执行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 09:34:58