Skip to content

Instantly share code, notes, and snippets.

@dmartinlozano
Created November 14, 2021 02:54
Show Gist options
  • Save dmartinlozano/dafb6923a0fd14db304ec40c6c3dc917 to your computer and use it in GitHub Desktop.
Save dmartinlozano/dafb6923a0fd14db304ec40c6c3dc917 to your computer and use it in GitHub Desktop.
flutter ReorderableListView with Slidable
class MyFile{
int? index;
String name;
String path;
MyFile({required this.name, required this.path, this.index});
Map<String, dynamic> toJson() => {
'name': name,
'path': path
};
MyFile.fromJson(Map<String, dynamic> json)
: name = json['name'],
path = json['path'];
}
extension IndexedIterable<E> on Iterable<E> {
Iterable<T> mapIndexed<T>(T Function(E value, int index) f) {
var index = 0;
return map((element) => f(element, index++));
}
}
body: ReorderableListView(
children: playList.mapIndexed((value, index){
value.index = index;
return value;
}).toList().map((file) =>
Slidable(
key: ObjectKey(file.path),
actions: <Widget>[
IconSlideAction(
icon: Icons.delete,
caption: 'Delete',
color: Colors.red,
onTap: () {
setState(() {
playList.removeAt(file.index!);
});
}
),
],
actionPane: SlidableDrawerActionPane(),
child: ListTile(
key: ObjectKey(file.path),
title: Text(file.name),
trailing: Icon(Icons.drag_handle)
)
)
).toList(),
onReorder: (int start, int current) {
// dragging from top to bottom
if (start < current) {
int end = current - 1;
MyFile startItem = playList[start];
int i = 0;
int local = start;
do {
playList[local] = playList[++local];
i++;
} while (i < end - start);
playList[end] = startItem;
}
// dragging from bottom to top
else if (start > current) {
MyFile startItem = playList[start];
for (int i = start; i > current; i--) {
playList[i] = playList[i - 1];
}
playList[current] = startItem;
}
setState(() {});
},
),
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment