ReorderableListView widget and Attributes

ReorderableListView widget and Attributes

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

  1. 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.

  2. 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);
    });
  },
)

Did you find this article valuable?

Support Vinit Mepani (Flutter Developer) by becoming a sponsor. Any amount is appreciated!