This widget allows you to create a list view where items can be repositioned and reordered by dragging and dropping. It’s particularly useful when you want to implement features like reordering items in a to-do list or rearranging elements in a custom order.
Constructors
ReorderableListView.builder:
Use this constructor when your list has a large number of items (e.g., loaded from APIs or a database).
Key parameters:
itemCount: The number of items in the list.
itemBuilder: A function to build list item widgets.
onReorder: A callback function that reports when an item has been dragged to a new location, allowing you to update the order of items.
ReorderableListView:
Convenient for smaller lists.
Key parameters:
children: A list of widgets representing the items.
onReorder: The same callback function as above.
The onReorder Function
The onReorder function is essential for handling the reordering logic. It receives two parameters:
oldIndex: The index of the item before it was moved.
newIndex: The index of the item after it has been moved.
Examples
1. ReorderableListView.builder
ReorderableListView.builder(
itemCount: _myListData.length,
itemBuilder: (context, index) {
return ListTile(
key: Key('$index'), // Required for reordering
title: Text(_myListData[index]),
);
},
onReorder: (oldIndex, newIndex) {
setState(() {
if (newIndex > oldIndex) {
newIndex = newIndex - 1;
}
final item = _myListData.removeAt(oldIndex);
_myListData.insert(newIndex, item);
});
},
)
2. ReorderableListView
ReorderableListView(
children: _myListData.map((item) {
return ListTile(
key: Key(item), // Required for reordering
title: Text(item),
);
}).toList(),
onReorder: (oldIndex, newIndex) {
setState(() {
if (newIndex > oldIndex) {
newIndex = newIndex - 1;
}
final item = _myListData.removeAt(oldIndex);
_myListData.insert(newIndex, item);
});
},
)