修正windows编译路径数据库问题

(cherry picked from commit 58f6dec2325bdf78689fb4894d76c0dd7b591df3)
This commit is contained in:
2025-10-29 15:29:00 +08:00
committed by speakeloudest
parent fbdf4a2337
commit 1970bbb6fd
+50 -2
View File
@@ -23,17 +23,65 @@ class KRSecureStorage {
// 初始化 Hive
Future<void> kr_initHive() async {
try {
if (Platform.isMacOS) {
// 根据不同平台指定数据库路径
if (Platform.isMacOS || Platform.isWindows || Platform.isLinux) {
final baseDir = await getApplicationSupportDirectory();
KRLogUtil.kr_i('初始化 Hive,路径: ${baseDir.path}', tag: 'SecureStorage');
await Hive.initFlutter(baseDir.path);
} else {
// Android 和 iOS 使用默认路径
await Hive.initFlutter();
}
// 使用加密适配器
final key = HiveAesCipher(_generateKey());
await Hive.openBox(_boxName, encryptionCipher: key);
} catch (e) {
KRLogUtil.kr_i('Hive 初始化成功', tag: 'SecureStorage');
} catch (e, stackTrace) {
KRLogUtil.kr_e('初始化 Hive 失败: $e', tag: 'SecureStorage');
KRLogUtil.kr_e('错误堆栈: $stackTrace', tag: 'SecureStorage');
// 对于 Windows 和 Linux,如果初始化失败,尝试删除旧文件并重试
if (Platform.isWindows || Platform.isLinux) {
try {
KRLogUtil.kr_i('尝试清理并重新初始化 Hive', tag: 'SecureStorage');
final baseDir = await getApplicationSupportDirectory();
final hiveDir = Directory(baseDir.path);
// 查找并删除相关的 Hive 文件
if (hiveDir.existsSync()) {
final files = hiveDir.listSync();
for (var entity in files) {
if (entity is File) {
final fileName = entity.path.split(Platform.pathSeparator).last;
// 删除 Hive 数据库文件(通常是 .hive 或 .lock 文件)
if (fileName.startsWith(_boxName) ||
fileName.endsWith('.hive') ||
fileName.endsWith('.lock')) {
try {
await entity.delete();
KRLogUtil.kr_i('已删除文件: $fileName', tag: 'SecureStorage');
} catch (deleteError) {
KRLogUtil.kr_e('删除文件失败: $deleteError', tag: 'SecureStorage');
}
}
}
}
}
// 重新初始化
await Hive.initFlutter(baseDir.path);
final key = HiveAesCipher(_generateKey());
await Hive.openBox(_boxName, encryptionCipher: key);
KRLogUtil.kr_i('Hive 重新初始化成功', tag: 'SecureStorage');
} catch (retryError, retryStack) {
KRLogUtil.kr_e('重新初始化 Hive 仍然失败: $retryError', tag: 'SecureStorage');
KRLogUtil.kr_e('重试堆栈: $retryStack', tag: 'SecureStorage');
rethrow;
}
} else {
rethrow;
}
}
}