Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onReorder() arguments in Flutter ReorderableListView

I try to create a reorderable list in Flutter with the ReorderableListView widget:

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

I can´t find an exact explanation of what the two arguments in onReorder are. I found some "oldIndex", "newIndex" staff - but that doesn´t look like it´s correct.

I´ve build an example with a List with three items. When I drag the items I get the following (for me confusing) results:

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

For me, it looks like a mixup of index and position...

Maybe someone has an idea what´s my mistake?

like image 709
Michael Avatar asked Jan 12 '19 18:01

Michael


1 Answers

It's old and new index, but it has problems. There are open issues for that, as you can see here.

Here's an example that shows how to use them:

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

You can see a demo here in this snippet.

As per my experience (2019/January), I gave up on the Flutter's ReorderableListView and started using knopp/flutter_reorderable_list. I even made a Widget to make that switch easier, check it out and see if it makes sense to you.

like image 65
Feu Avatar answered Sep 28 '22 01:09

Feu