ReorderableListView() is a built-in widget in the flutter that enables the user to change the order of the items placed in the ListView through a long tap and drag.
A reminder app or a task manager app would be the perfect example of this. These apps usually provide reorder or sort functionalities. As in these apps, the user needs to be able to arrange/sort items based on his/her preferences or order priority.
This is pretty easy to implement in the flutter. So, let’s check how to implement Reorderable ListView in Flutter.
You can also check out our Flutter app development company page for developing Flutter apps.
Step 1: Create a flutter project.
Step 2: First, we will create a list that has data. So, we will create a list of strings and names as tasks.
1 2 |
List<String> tasks = ["A Task", "B Task", "C Task", "D Task", "E Task", "F Task","G Task","H Task"]; |
Step 3: Add the ReorderableListView() widget and add the key in the children of the ReorderableListView widget. The key is expected to distinguish the items after their position is changed.
1 2 3 4 5 6 7 8 9 |
Container(padding: const EdgeInsets.all(8.0), child: ReorderableListView( children: [ for(final task in tasks) Card(color: Colors.lightBlueAccent.shade100, key: ValueKey(task), elevation: 5.0, child: ListTile(title: Text(task), leading: const Icon(Icons.work, color: Colors.black),),), ],)) |
Step 4: Add the reorder function. It is a callback function used by the list to report that a list item has been dragged to a new location in the list and the application should update the order of the items.
1 2 3 4 5 6 7 8 9 |
onReorder:(oldIndex,newIndex ){ setState(() { if(newIndex > oldIndex){ newIndex = newIndex-1; } }); final task = tasks.removeAt(oldIndex); tasks.insert(newIndex, task); } |
Now run your code and check by long-tapping on an item and dragging it to a new position.
Output:
So, this is how we implement reorderable listview in Flutter.
Thanks for reading this article ❤
If I got something wrong, let me know in the comments. I would love to improve.
Reference Link: https://www.kindacode.com/article/working-with-reorderablelistview-in-flutter/