Sorting items programatically does not update DragAndDropList.
myleftshoe opened this issue · 5 comments
If the order of the list of items passed to DragAndDropList is changed by some other means than dragging and dropping, e.g. by doing removeAt or insert somewhere other than in onDragFinish the changes are not reflected. I.e the list is not re-ordered.
I'm pretty new to flutter so I changed DragAnDropList to a ListView for comparison and the changes were reflected.
What I am trying to do is allow the user to do a quick initial sort by tapping items. Tapping an item moves it to the top of the list with an indicator 1, 2, 3, 4, ... for each item tapped. So have an onTap() which does an insert and removeAt. As mentioned it works with a ListView but not with DragAndDropList. (ListView takes an itemBuilder that accepts an index rather than the item, that was the only change I made to the itemBuilder to get it to work with ListView)
I appreciate the work you have done, thanks again! I also understand that it may already meet your requirements so no offence taken if you decide not to spend more time on addressing something that you yourself don't need.
Did you wrap your removeAt and insert in a setState() ?
Yes but didn't work, I've now copied your code and added a gesture detector with onTap and got it working by doing the insert and removeAt directly on the "rows" List. That will do for now.
Hey @Norbert515 , as DragAndDropList creates a new list from the rowsData passed to it, I think all that needs to be done is to implement a didUpdateWidget method for _DragAndDropListState. This seems to work (i.e the list is updated when items are added or removed "by some other means"):
@override
void didUpdateWidget(DragAndDropList<T> oldWidget) {
super.didUpdateWidget(oldWidget);
List data = widget.rowsData;
rows = data.map((it) => new Data<T>(it)).toList();
key.clear();
for (int i = 0; i < rows.length; i++) {
key.add(new GlobalKey());
}
}
This was a quick fix, (just copied your initState code) - according to the flutter docs the Global keys are relatively expensive so it's probably not good to clear then recreate them all.
You can create a pull request if you want to. I know global keys are expensive but looking at the code I think getting the state is the expensive operation. And the state only gets requested once the drag starts. Do you know if that's correct?
Added it to the code