flutter 无法更改项目在配置单元数据库中的位置

whhtz7ly  于 2022-12-14  发布在  Flutter
关注(0)|答案(1)|浏览(144)

无法交换配置单元数据库中记录的位置,出现类似“未处理的异常”的错误:HiveError:HiveObject的同一示例不能使用两个不同的键(“5”和“10”)存储。
密码:

Box<CounterDetails> box = await Hive.openBox<CounterDetails>(kHiveBoxName);

 if (oldIndex < newIndex) {
   newIndex -= 1;
 }
// this is required, before you modified your box;
final oldItem = box.getAt(oldIndex);
final newItem = box.getAt(newIndex);

// here you just swap this box item, oldIndex <> newIndex
box.putAt(oldIndex, newItem!);
box.putAt(newIndex, oldItem!);
qxsslcnc

qxsslcnc1#

对于错误,你可以在CounterDetails上创建copyWith方法,它将返回新的示例。或者创建复制字段的新示例。然后把这个新对象。
copyWith方法将类似于

class CounterDetails {
  final String a;
  CounterDetails({
    required this.a,
  });

  CounterDetails copyWith({
    String? a,
  }) {
    return CounterDetails(
      a: a ?? this.a,
    );
  }
}

把这些放在一起就像

box.putAt(oldIndex, newItem!.copyWith()); //better do a null check 1st , same for next  one

相关问题