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

Flutter解压加密Zip遇Unsupported operation错误求助

解决Flutter解压加密Zip时的"Cannot modify an unmodifiable list"错误

问题场景

使用archive库从Flutter assets加载加密Zip包并解压时,触发如下错误:

E/flutter ( 8813): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: Unsupported operation: Cannot modify an unmodifiable list
E/flutter ( 8813): #0      _UnmodifiableUint8ArrayView.[]= (dart:typed_data-patch/typed_data_patch.dart:5391:5)
E/flutter ( 8813): #1      ZipFile._decodeZipCrypto (package:archive/src/zip/zip_file.dart:192:12)
E/flutter ( 8813): #2      ZipFile.content (package:archive/src/zip/zip_file.dart:129:27)
E/flutter ( 8813): #3      ZipDecoder.decodeBuffer (package:archive/src/zip_decoder.dart:32:41)
E/flutter ( 8813): #4      ZipDecoder.decodeBytes (package:archive/src/zip_decoder.dart:16:12)
E/flutter ( 8813): #5      _HomePageState.dataWriteToLocal (package:mytest/Pages/home_page.dart:417:36)
E/flutter ( 8813): <asynchronous suspension>

问题原因

从rootBundle.load()获取的ByteData,其buffer.asUint8List()返回的是不可修改的Uint8Array视图。而archive库解密加密Zip文件时,需要直接修改字节数组内容,操作不可修改列表就会触发该错误。

解决方案

将不可修改的Uint8List转换为可修改的列表副本,以下是修改后的完整代码:

var byteData = await rootBundle.load('assets/res.zip');
var buffer = byteData.buffer;
// 将不可修改的Uint8List转为可修改的列表副本
var bytes = List<int>.from(buffer.asUint8List());
// 也可以用 buffer.asUint8List().toList() 实现相同效果
var archive = ZipDecoder().decodeBytes(bytes, verify: true, password: '123');

for (final file in archive) {
  final filename = file.name;
  if (file.isFile) {
    final data = file.content as List<int>;
    File('$tempPath/files/$filename')
      ..createSync(recursive: true)
      ..writeAsBytesSync(data);
  } else {
    Directory('$tempPath/files/$filename').create(recursive: true);
  }
}

关键修改说明

把原代码中直接传入的buffer.asUint8List()替换为List<int>.from(buffer.asUint8List())或buffer.asUint8List().toList(),生成可修改的字节列表副本,确保archive库解密时能正常操作数组内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 18:56:15