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

如何实现Isar数据库本地备份及卸载重装后的恢复?

Isar数据库备份与恢复的实现方式

方式一:直接复制Isar数据库文件(最简便高效)

Isar数据库以文件形式存储在应用沙箱中,直接复制核心数据库文件即可完成全量备份,恢复时覆盖原路径文件即可。

实现步骤:

  1. 获取数据库文件路径
    通过Isar实例的directory属性获取数据库所在目录,核心文件为.isar后缀的主文件(.lock锁文件可忽略):

    final isar = Isar.getInstance();
    final dbDir = isar!.directory;
    final dbFile = File('$dbDir/your_schema_name.isar'); // 替换为你的Schema名称
    
  2. 备份到目标存储
    选择SD卡或公共存储目录(如Android的Download、iOS的Documents),复制文件前需确保目录存在:

    // 示例:备份到Android Download目录
    final backupDir = Directory('/storage/emulated/0/Download/isar_backups');
    await backupDir.create(recursive: true);
    final backupFile = File('${backupDir.path}/isar_backup_${DateTime.now().millisecondsSinceEpoch}.isar');
    await dbFile.copy(backupFile.path);
    
  3. 恢复数据库
    重装应用后,先关闭Isar实例,再将备份文件复制回原数据库路径:

    // 先关闭已打开的Isar实例
    final tempIsar = await Isar.open([YourSchema]);
    await tempIsar.close();
    
    // 复制备份文件到数据库目录
    final backupFile = File('/storage/emulated/0/Download/isar_backups/xxx.isar'); // 备份文件名
    final targetFile = File('${tempIsar.directory}/your_schema_name.isar');
    await backupFile.copy(targetFile.path);
    
    // 重新打开数据库完成恢复
    final restoredIsar = await Isar.open([YourSchema]);
    

方式二:使用Isar内置JSON导出/导入API(跨平台兼容)

Isar为每个集合提供exportJson和importJson方法,可将数据导出为JSON格式,适合需要可读性或跨平台迁移的场景。

实现步骤:

  1. 导出全量数据到JSON文件
    遍历所有集合,导出每个集合的JSON数据并合并写入文件:

    final isar = Isar.getInstance();
    final backupDir = Directory('/storage/emulated/0/Download/isar_backups');
    await backupDir.create(recursive: true);
    final backupFile = File('${backupDir.path}/isar_full_backup.json');
    
    final allCollectionData = <String, dynamic>{};
    for (final collection in isar!.collections) {
      final jsonData = await collection.exportJson();
      allCollectionData[collection.name] = jsonData;
    }
    
    await backupFile.writeAsString(jsonEncode(allCollectionData));
    
  2. 从JSON文件恢复数据
    读取备份文件,遍历每个集合的JSON数据并导入:

    final isar = await Isar.open([YourSchema]);
    final backupFile = File('/storage/emulated/0/Download/isar_backups/isar_full_backup.json');
    final jsonString = await backupFile.readAsString();
    final allData = jsonDecode(jsonString) as Map<String, dynamic>;
    
    for (final entry in allData.entries) {
      final collection = isar.collectionByName(entry.key);
      if (collection != null) {
        await collection.importJson(entry.value);
      }
    }
    

方式三:自定义二进制序列化备份(高性能大场景)

若数据量庞大,追求备份效率和体积,可使用Protobuf、MessagePack等二进制序列化方式,自定义处理实体的序列化逻辑。

实现思路:

  1. 为Isar实体类编写Protobuf/MessagePack定义,生成序列化代码;
  2. 批量读取集合数据,将实体序列化为二进制字节;
  3. 将字节写入备份文件,恢复时反序列化为实体后批量插入Isar。

代码片段(Protobuf示例):

// 假设已生成User实体的Protobuf序列化代码
final isar = Isar.getInstance();
final users = await isar!.users.where().findAll();

// 序列化所有User为二进制
final backupBytes = <List<int>>[];
for (final user in users) {
  final protoUser = ProtoUser()
    ..id = user.id
    ..name = user.name
    ..email = user.email;
  backupBytes.add(protoUser.writeToBuffer());
}

// 写入备份文件(需实现字节拼接逻辑)
final backupFile = File('/storage/emulated/0/Download/isar_backups/users_backup.bin');
await backupFile.writeAsBytes(concatenateBytes(backupBytes));

// 恢复流程
final bytes = await backupFile.readAsBytes();
final restoredUsers = <User>[];
// 按Protobuf格式分割字节并反序列化(需处理分割逻辑)
for (final chunk in splitBytes(bytes)) {
  final protoUser = ProtoUser.fromBuffer(chunk);
  restoredUsers.add(User(
    id: protoUser.id,
    name: protoUser.name,
    email: protoUser.email,
  ));
}

// 批量插入Isar
await isar.writeTxn(() => isar.users.putAll(restoredUsers));

关键注意事项:

  • 权限处理:Android 9及以下需申请WRITE_EXTERNAL_STORAGE权限;Android 10+建议使用Scoped Storage API或path_provider插件获取合法存储路径;iOS需配置Documents目录访问权限。
  • 数据一致性:备份前需确保Isar无写入操作,可通过事务或临时关闭数据库保证数据完整性。
  • 备份时机:建议由用户主动触发备份,或在应用前台退出时执行(避免后台任务被系统终止)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 23:30:18