Flutter Sortable Drag And Drop ListView
You can use native flutter widget, ReorderableListView
to achieve it, here is the example of doing it.
List<String> _list = ["Apple", "Ball", "Cat", "Dog", "Elephant"];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: ReorderableListView(
children: _list.map((item) => ListTile(key: Key("${item}"), title: Text("${item}"), trailing: Icon(Icons.menu),)).toList(),
onReorder: (int start, int current) {
// dragging from top to bottom
if (start < current) {
int end = current - 1;
String startItem = _list[start];
int i = 0;
int local = start;
do {
_list[local] = _list[++local];
i++;
} while (i < end - start);
_list[end] = startItem;
}
// dragging from bottom to top
else if (start > current) {
String startItem = _list[start];
for (int i = start; i > current; i--) {
_list[i] = _list[i - 1];
}
_list[current] = startItem;
}
setState(() {});
},
),
);
}
Flutter itself provides a (Material) ReorderableListView class.
I've tried flutter_reorderable_list and dragable_flutter_list but none of them worked properly - there was some unwanted artifacts during dragging. So I've tried to make own solution:
ListView.builder(
itemBuilder: (context, index) => buildRow(index),
itemCount: trackList.length,
),
Widget buildRow(int index) {
final track = trackList[index];
ListTile tile = ListTile(
title: Text('${track.getName()}'),
);
Draggable draggable = LongPressDraggable<Track>(
data: track,
axis: Axis.vertical,
maxSimultaneousDrags: 1,
child: tile,
childWhenDragging: Opacity(
opacity: 0.5,
child: tile,
),
feedback: Material(
child: ConstrainedBox(
constraints:
BoxConstraints(maxWidth: MediaQuery.of(context).size.width),
child: tile,
),
elevation: 4.0,
),
);
return DragTarget<Track>(
onWillAccept: (track) {
return trackList.indexOf(track) != index;
},
onAccept: (track) {
setState(() {
int currentIndex = trackList.indexOf(track);
trackList.remove(track);
trackList.insert(currentIndex > index ? index : index - 1, track);
});
},
builder: (BuildContext context, List<Track> candidateData,
List<dynamic> rejectedData) {
return Column(
children: <Widget>[
AnimatedSize(
duration: Duration(milliseconds: 100),
vsync: this,
child: candidateData.isEmpty
? Container()
: Opacity(
opacity: 0.0,
child: tile,
),
),
Card(
child: candidateData.isEmpty ? draggable : tile,
)
],
);
},
);
}
I guess, this is not the best solution, and I'm maybe will change it further, but for now it works quite well