【问题标题】:Flutter & Hive - How to Save Reordered List in HiveFlutter & Hive - 如何在 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>
    });
  }

【问题讨论】:

标签: list flutter save flutter-hive reorderable-list


【解决方案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);
  });
}

【讨论】:

    猜你喜欢
    • 2020-10-17
    • 2022-01-17
    • 2020-09-23
    • 2022-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-03
    • 1970-01-01
    相关资源
    最近更新 更多