38 lines
1.2 KiB
Dart
38 lines
1.2 KiB
Dart
import 'dart:io';
|
|
|
|
import 'package:flutter/services.dart';
|
|
import 'package:path_provider/path_provider.dart';
|
|
|
|
class SCFileHelper{
|
|
// 将资源文件拷贝到应用文档目录
|
|
static Future<String> copyAssetToLocal(String assetPath) async {
|
|
|
|
try {
|
|
// 获取应用文档目录
|
|
final Directory appDocDir = await getApplicationDocumentsDirectory();
|
|
final String localFilePath = '${appDocDir.path}/${assetPath.split('/').last}';
|
|
|
|
// 检查文件是否已存在
|
|
if (await File(localFilePath).exists()) {
|
|
print('文件已存在,直接使用: $localFilePath');
|
|
return localFilePath;
|
|
}
|
|
|
|
// 从Assets加载字节数据
|
|
final ByteData data = await rootBundle.load(assetPath);
|
|
final List<int> bytes = data.buffer.asUint8List();
|
|
|
|
// 将字节数据写入本地文件
|
|
final File localFile = File(localFilePath);
|
|
await localFile.writeAsBytes(bytes);
|
|
|
|
print('文件拷贝成功: $localFilePath');
|
|
return localFilePath;
|
|
} catch (e) {
|
|
print('拷贝文件时发生错误: $e');
|
|
rethrow; // 重新抛出异常以便上层处理
|
|
} finally {
|
|
|
|
}
|
|
}
|
|
} |