Home > Software engineering >  Not able to change the postion of items in hive database
Not able to change the postion of items in hive database

Time:12-10

Not able to swap the position of the record in hive database getting error like Unhandled Exception: HiveError: The same instance of an HiveObject cannot be stored with two different keys ("5" and "10").

code:

  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!);

CodePudding user response:

As for the error, you can create copyWith method on CounterDetails that will return new instance. Or create new instance duplicating fields. Then put this new object.

The copyWith method will be like

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


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

And putting those will be like

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