extractAsset function
从 assets 解压文件
assetPath assets 里的原始路径
rename (可选) 解压后的目标文件名。如果不传,则使用原始文件名。
update 是否强制覆盖
Implementation
Future<String> extractAsset(
String assetPath, {
String? rename,
bool update = false,
}) async {
Directory appDir = await getApplicationSupportDirectory();
// 如果指定了 customName,就用它;否则用原始文件名
String fileName = rename ?? assetPath.split('/').last;
String realPath = '${appDir.path}/$fileName';
File file = File(realPath);
// 检查文件是否存在
if (!update && await file.exists()) {
devlog('[extractAsset] ⏭️ 文件已存在,跳过: $fileName');
// Linux/Mac 下需要确保有执行权限
if (!Platform.isWindows) {
await Process.run('chmod', ['+x', realPath]);
}
return realPath;
}
// 读取并写入
try {
ByteData data = await rootBundle.load(assetPath);
await file.writeAsBytes(data.buffer.asUint8List());
// Linux/Mac 赋予执行权限
if (!Platform.isWindows) {
await Process.run('chmod', ['+x', realPath]);
}
devlog('[extractAsset] ✅ 已解压: $assetPath -> $realPath');
} catch (e) {
devlog('[extractAsset] ❌ 解压失败: $e');
rethrow;
}
return realPath;
}