Flutter ReorderableListView 中的 onReorder() 参数

Mic*_*ael 9 dart flutter reorderable-list

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

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

我找不到 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
Run Code Online (Sandbox Code Playgroud)

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

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

Mar*_*cel 11

根据有关ReorderCallback的文档,oldIndexnewIndex被传递给回调。甚至给出了一个示例,说明如何使用回调来实际订购 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);
}
Run Code Online (Sandbox Code Playgroud)


Feu*_*Feu 8

它是旧索引和新索引,但它有问题。如您所见,这里有一些未解决的问题。

这是一个显示如何使用它们的示例:

onReorder: (oldIndex, newIndex) {
  setState(() {
    // These two lines are workarounds for ReorderableListView problems
    if (newIndex > _sampleItems.length) newIndex = _sampleItems.length;
    if (oldIndex < newIndex) newIndex--;

    MyItem item = _sampleItems[oldIndex];
    _sampleItems.remove(item);
    _sampleItems.insert(newIndex, item);
  });
},
Run Code Online (Sandbox Code Playgroud)

你可以在这个片段中看到一个演示。

根据我的经验(2019/1 月),我放弃了 Flutter 的 ReorderableListView 并开始使用knopp/flutter_reorderable_list。我什至制作了一个Widget 使切换更容易,检查一下,看看它是否对你有意义。