Flutter ObjectBox如何仅更新实体的特定列?
解决ObjectBox更新实体特定列的问题
问题原因
你直接创建新的Customer对象并调用put时,只传入了id和city,name会使用构造函数的默认值空字符串。ObjectBox的put方法会根据id覆盖已有实体,导致原name被清空。
解决方案
要更新特定列,需先查询出原实体,保留不需要修改的字段,再更新目标字段后保存。以下是具体步骤:
1. 给实体类添加copyWith方法
因为你的name和city是final字段,无法直接修改,添加copyWith方法可以方便地创建保留原字段值的新对象:
@Entity() class Customer { int id; final String name; final String city; Customer({this.id = 0, this.name = "", this.city = ""}); // 用于复制对象并修改指定字段 Customer copyWith({int? id, String? name, String? city}) { return Customer( id: id ?? this.id, name: name ?? this.name, city: city ?? this.city, ); } }
2. 修改更新逻辑
先查询对应id的原实体,再用copyWith创建仅修改city的新对象,最后调用put保存:
// 修正strInput的定义,应为字符串而非List String strInput = "1,Tokyo"; List<String> lstr = strInput.split(","); int idUpdate = int.tryParse(lstr[0]) ?? 0; if (idUpdate > 0) { // 查询原实体 Customer? existingCustomer = customerBox.get(idUpdate); if (existingCustomer != null) { // 仅更新city,保留原name和id Customer updatedCustomer = existingCustomer.copyWith(city: lstr[1]); customerBox.put(updatedCustomer); } }
补充说明
如果你的实体字段不是final,可以直接查询后修改字段再put,无需copyWith:
if (idUpdate > 0) { Customer? existingCustomer = customerBox.get(idUpdate); if (existingCustomer != null) { existingCustomer.city = lstr[1]; customerBox.put(existingCustomer); } }
但推荐使用final字段+copyWith的方式,保持实体的不可变性,避免意外修改。
内容的提问来源于stack exchange,提问作者arif zein
相关产品推荐
相关产品推荐

