首页 > 解决方案 > Flutter ReorderableListView 中的 onReorder() 参数

问题描述

我尝试使用 ReorderableListView 小部件在 Flutter 中创建一个可重新排序的列表

return ReorderableListView(
    onReorder: (int index, int targetPosition) {
        print(index.toString() + " -> " + targetPosition.toString());
    }
...

我找不到关于 onReorder 中的两个参数的确切解释。我找到了一些“oldIndex”、“newIndex”员工——但这看起来并不正确。

我已经建立了一个包含三个项目的列表的示例。当我拖动项目时,我得到以下(让我感到困惑)结果:

Position 1 -> Position 2 results in 0 -> 2
Position 1 -> Position 3 results in 0 -> 3
Position 3 -> Position 1 results in 2 -> 1

对我来说,它看起来像是索引和位置的混合......

也许有人知道我的错误是什么?

标签: flutterdartreorderable-list

解决方案


根据有关ReorderCallback的文档,oldIndexandnewIndex被传递给回调。甚至还有一个关于如何使用回调来实际订购 a 中的项目的示例List

final List<MyDataObject> backingList = <MyDataObject>[/* ... */];

void handleReorder(int oldIndex, int newIndex) {
  if (oldIndex < newIndex) {
    // removing the item at oldIndex will shorten the list by 1.
    newIndex -= 1;
  }
  final MyDataObject element = backingList.removeAt(oldIndex);
  backingList.insert(newIndex, element);
}

推荐阅读