Flutter & Hive - How to Save Reordered List in Hive

1.1k views Asked by At

I'm a beginner with Flutter and I'm currently implementing a local Save of Items using Hive and Boxes. Everything was okay until I decided to reorder the list of Items.

My question is: How can I save the reordered changes, knowing that I can't use the traditional InsertAt(index) and RemoveAt(index) with Hive.


  Box<Item> itemsBox;
  List<Item> items; //Item class extends HiveObject

  void addItem(Item item) {
    setState(() {
      items.add(item);
      itemsBox.add(item);
    });
  }

  void removeItem(Item item) {
    setState(() {
      items.remove(item);
      item.delete(); 
    });
  }



  void _onReorder(int oldIndex, int newIndex) {
    setState(() {
      Item row = items.removeAt(oldIndex);
      items.insert(newIndex, row);

      int lowestInt = (oldIndex < newIndex) ? oldIndex : newIndex;
      int highestInt = (oldIndex > newIndex) ? oldIndex : newIndex;

      // What Can I Do with my box to save my List<Item> items
      // Box is a Box<Item>
    });
  }
1

There are 1 answers

0
Khen Solomon Lethil On

I was looking for the answer too, it has turned out pretty easy.

void _onReorder(int oldIndex, int newIndex) {
  if (oldIndex < newIndex) {
    newIndex -= 1;
  }
  setState(() {
    // this is required, before you modified your box;
    final oldItem = itemsBox.getAt(oldIndex);
    final newItem = itemsBox.getAt(newIndex);
    
    // here you just swap this box item, oldIndex <> newIndex
    itemsBox.putAt(oldIndex, newItem);
    itemsBox.putAt(newIndex, oldItem);
  });
}