I am using the ReorderableListView widget to display a list in my Flutter application..
Everything works fine and the ListTiles easily get dragged and dropped to new positions but the only thing is that they don't stay in the new position after restarting the application.
How do I maintain their positions? I tried using PageStorage but it doesn't maintain the new positions
Any ideas?
Thanks in advance
ReorderableListView(
physics: const ClampingScrollPhysics(),
shrinkWrap: true,
onReorder: (int oldIndex, int newIndex) {
setState(() {
if (newIndex > oldIndex) newIndex--;
final item = tasks.removeAt(oldIndex);
tasks.insert(newIndex, item);
});
},
children: [
for (final item in tasks)
Container(
key: ValueKey(item),
child: ExpansionTile(
title: Text(item['name'])
)])
I would suggest creating a Task class and adding an id field that uniquely identifies the task:
Then you'll need to use a storage package like shared_preferences to save the index of each task whenever they are reordered:
The code is a little complicated and it will only be suitable for small lists. In short, whenever a item in the list moves, you need to save its new index to shared preferences. The trick is that newIndex is always one greater than the actual new index.
You also need to handle forward and backward movement differently. On forward moves, all of the items between the old and new index need to be updated since their order value would have decreased. For backward moves, it is the opposite.