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

如何在ObjectBox Dart模型变更时接收通知并执行数据迁移?

ObjectBox Dart 模型迁移与变更通知处理

一、模型变更时的迁移操作(填充新列数据)

  • 模型变更后的数据迁移需通过openStore的migrations参数配置,结合实体类版本号触发:
    1. 先更新实体类的@Entity注解版本,比如新增字段后,将@Entity(version: 1)改为@Entity(version: 2)。
    2. 在openStore中配置对应版本的迁移逻辑,实现新列的数据填充:
      final store = await openStore(
        migrations: {
          2: (migrator) async {
            final entityBox = migrator.store.box<YourTargetEntity>();
            // 遍历所有现有实体,为新字段赋值
            await entityBox.query().forEach((entity) {
              // 可根据实体已有数据计算新字段值,或设置默认值
              entity.newColumn = "默认填充值";
              entityBox.put(entity);
            });
          },
        },
      );
      

二、接收模型变更的通知

ObjectBox没有提供全局的模型结构变更通知,但可通过两种方式实现需求:

  • 监听实体数据的增删改操作:如果关注实体数据的变化,使用Box的subscribe方法监听:
    final targetBox = store.box<YourTargetEntity>();
    final dataSubscription = targetBox.subscribe().listen((changeEvent) {
      // changeEvent.type 包含增/删/改操作类型
      print("实体ID ${changeEvent.entityId} 执行了 ${changeEvent.type} 操作");
    });
    // 不再需要监听时记得取消订阅
    // dataSubscription.cancel();
    
  • 迁移完成时自定义通知:如果需要感知模型结构变更(即迁移完成事件),在迁移逻辑中嵌入自定义通知,比如用Stream转发事件:
    // 定义全局的StreamController
    final migrationStream = StreamController<MigrationInfo>.broadcast();
    
    // 在迁移配置中添加通知逻辑
    final store = await openStore(
      migrations: {
        2: (migrator) async {
          // 执行迁移逻辑...
          migrationStream.add(MigrationInfo(updatedVersion: 2));
        },
      },
    );
    
    // 在应用其他地方监听迁移完成事件
    migrationStream.stream.listen((info) {
      print("模型已迁移到版本 ${info.updatedVersion}");
    });
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 08:12:45