Flutter Hive关联CartTable与OrdersTable时出现HiveObjects入盒错误求助
问题解决:Hive中CartTable与OrdersTable关联报错
错误HiveObjects needs to be in the box 'orders'的核心原因是:你要添加到HiveList的OrdersTable对象,还没有被存入对应的'orders' Box中。HiveList本质是对Box中对象的引用集合,只能包含已经存在于目标Box里的HiveObject。
修正后的代码实现:
Box<CartTable> _cartTable = Hive.box<CartTable>('cart'); Box<OrdersTable> _orders = Hive.box<OrdersTable>('orders'); CartTable? cart; cart = CartTable() ..id = store.id ..name = store.name ..image = store.image; // 初始化HiveList cart.orders = HiveList(_orders); final order = OrdersTable() ..id = menu.id ..name = menu.name ..description = menu.description! ..image = menu.image ..price = menu.price ..note='' ..detail='' ..promotionCode='' ..count = 1; // 关键步骤:先将order存入对应的'orders' Box await _orders.add(order); // 或者调用 order.save(),效果一致 // 此时order已在Box中,可安全添加到HiveList cart.orders.add(order); // 保存cart到对应的Box await _cartTable.add(cart); await cart.save();
额外说明:
- HiveList本身不会存储对象的副本,只存储对象在目标Box中的引用ID,所以必须确保对象先被持久化到对应Box。
- 如果后续需要从HiveList中移除对象,直接调用
cart.orders.remove(order)即可,Hive会自动维护引用关系,无需手动删除Box中的对象(除非你明确要删除)。
内容的提问来源于stack exchange,提问作者DolDurma
相关产品推荐
相关产品推荐

