getAbsolutePathFromAsset method
Implementation
Future<String> getAbsolutePathFromAsset(String assetPath) async {
// 如果路径为空,直接返回
if (assetPath.isEmpty) {
return '';
}
// 检查缓存
if (assetPathCache.containsKey(assetPath)) {
final cachedPath = assetPathCache[assetPath]!;
// 验证缓存文件是否仍然存在
if (await File(cachedPath).exists()) {
return cachedPath;
} else {
// 缓存文件不存在,移除缓存
assetPathCache.remove(assetPath);
}
}
// 判断是否为 asset 路径(以 assets/ 开头)
if (assetPath.startsWith('assets/')) {
try {
// 对于 package 中的 asset,需要使用 packages/package_name/ 前缀
// 尝试两种路径:package 路径和直接路径(兼容主应用的 asset)
String bundlePath = 'packages/tcic_client_ui/$assetPath';
ByteData data;
try {
// 首先尝试 package 路径
data = await rootBundle.load(bundlePath);
} catch (e) {
// 如果 package 路径失败,尝试直接路径(主应用的 asset)
try {
data = await rootBundle.load(assetPath);
} catch (e2) {
TCICLog.error("Failed to load asset from both paths: $assetPath, error: $e2", actionModule: ActionModule.tcicController.name, actionName: ActionName.getAbsolutePathFromAsset.name);
return '';
}
}
final Uint8List bytes = data.buffer.asUint8List();
// 获取临时目录
final documentDir = await getApplicationDocumentsDirectory();
final cacheDir = Directory('${documentDir.path}/tcic_virtual_bg');
// 确保缓存目录存在
if (!await cacheDir.exists()) {
await cacheDir.create(recursive: true);
}
// 从 asset 路径生成文件名(例如:assets/images/bg/classroom.png -> classroom.png)
final fileName = assetPath.split('/').last;
final filePath = '${cacheDir.path}/$fileName';
// 写入文件
final file = File(filePath);
await file.writeAsBytes(bytes);
// 缓存路径
assetPathCache[assetPath] = file.path;
TCICLog.info("Successfully converted asset to file: $assetPath -> ${file.path}", actionModule: ActionModule.tcicController.name, actionName: ActionName.getAbsolutePathFromAsset.name);
return file.path;
} catch (e) {
TCICLog.error("Failed to load asset $assetPath: $e", actionModule: ActionModule.tcicController.name, actionName: ActionName.getAbsolutePathFromAsset.name);
// 如果加载失败,返回空字符串
return '';
}
}
// 如果是网络 URL(以 http:// 或 https:// 开头),直接返回
// TRTC SDK 可能支持网络 URL,如果不支持,需要先下载
if (assetPath.startsWith('http://') || assetPath.startsWith('https://')) {
// 可以在这里添加下载逻辑,如果需要的话
// 目前直接返回 URL,让 TRTC SDK 处理
return assetPath;
}
// 其他情况(可能是绝对路径),直接返回
return assetPath;
}