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?
According to the documentation regarding the ReorderCallback , the oldIndex
and newIndex
gets passed to the callback. There's even an example given on how the callback could be used to actually order items in 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);
}
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.
The onReorder function is written wrong in most tutorials. I think this one I just wrote is working.
void _onReorder(int oldIndex, int newIndex) {
setState(() {
newIndex > oldIndex ? (){newIndex--; int row = V755.removeAt(oldIndex);
V755.insert(newIndex, row);}() : (){int row = V755.removeAt(oldIndex);V755.insert(newIndex, row);}();
});
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.