Flutter & Hive - 如何在 Hive 中保存重新排序的列表

Posted

技术标签:

【中文标题】Flutter & Hive - 如何在 Hive 中保存重新排序的列表【英文标题】:Flutter & Hive - How to Save Reordered List in Hive 【发布时间】:2021-01-22 03:55:45 【问题描述】:

我是 Flutter 的初学者,我目前正在使用 Hive 和 Boxes 实现项目的本地保存。 在我决定重新排序项目列表之前,一切都很好。

我的问题是:我知道我不能将传统的 InsertAt(index)RemoveAt(index) 与 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>
    );
  

【问题讨论】:

getAt(index), deleteAt(index) 在 Hive 中被支持。 docs.hivedb.dev/#/basics/auto_increment 【参考方案1】:

我也在寻找答案,结果很简单。

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

【讨论】:

以上是关于Flutter & Hive - 如何在 Hive 中保存重新排序的列表的主要内容,如果未能解决你的问题,请参考以下文章