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

Flutter ObjectBox迁移报错:索引ID与现有UID不匹配

解决Flutter ObjectBox迁移时索引UID不匹配的10501错误

问题根源

修改实体属性名后执行flutter pub run build_runner build,objectbox-model.json中所有indexId被重新生成,与现有数据库存储的索引UID不一致,触发10501错误:

ObjectBoxException (ObjectBoxException: failed to create store: 10501 Incoming index ID 1:4292904108897114889 does not match existing UID 6540362680558265679)

你已为实体和属性指定固定UID,但忽略了索引同样需要稳定UID来保持迁移兼容性。

解决方案

方法1:通过注解为索引绑定固定UID

在@Index、@Unique注解中添加uid参数,直接锁定索引的唯一标识,build_runner后续执行时会保留该UID不会重新生成:

@Entity(uid: 1111111111111111111)
class ChildType {
  @Property(uid: 2222222222222222222)
  int id = 0;

  @Property(uid: 3333333333333333333)
  final parent = ToOne<ParentType>();

  @Unique(uid: 4444444444444444444, onConflict: ConflictStrategy.replace)
  String childName;

  @Index(uid: 3453453453453453453)
  @Property(uid: 5555555555555555555, type: PropertyType.date)
  DateTime childBirthday;
}

@Entity(uid: 6666666666666666666)
class ParentType {
  @Property(uid: 7777777777777777777)
  int id = 0;

  @Backlink("parent")
  final children = ToMany<ChildType>();

  @Unique(uid: 8888888888888888888, onConflict: ConflictStrategy.replace)
  String parentName;

  @Index(uid: 5675675675675675675)
  @Property(uid: 9999999999999999999, type: PropertyType.date)
  DateTime parentBirthday;
}

注:@Unique本质是唯一索引,必须指定uid避免重置;关系属性的隐式索引会随关联属性的UID稳定而保持不变。

方法2:手动固定objectbox-model.json中的indexId

若无法升级到支持@Index(uid)的ObjectBox版本,可手动编辑objectbox-model.json,保留已生成的indexId值:

  1. 执行build_runner前备份objectbox-model.json
  2. 执行build后,将备份文件中的indexId值覆盖回新生成的文件中:
"entities": [
  {
    "id": "1:1111111111111111111",
    "properties" : [
      // ...
      {
        "id": "3:4444444444444444444",
        "name": "childName",
        "indexId": "2:2342342342342342342" // 保留原有值不修改
      },
      {
        "id": "4:5555555555555555555",
        "name": "childBirthday",
        "indexId": "3:3453453453453453453" // 保留原有值不修改
      }
    ]
  }
]

注意事项

  • 所有带索引的属性(包括@Index、@Unique、关系隐式索引)都需固定UID,否则任意实体变更都可能触发索引UID重置。
  • 索引UID一旦指定不可随意修改,否则会再次触发迁移冲突。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 22:25:05