top of page

Flutter: ReorderableListView Widget Tutorial

Updated: Nov 27, 2022

ReorderableListView is a list of widgets that the user can drag at their own choice and can change their order. This widget is provided by the Flutter framework and no plugin is needed to be installed. This widget is appropriate for a small number of widgets because the reordering is done for each of the children even if not in view hence a CPU-intensive process.

Syntax

ReorderableListView is itself a widget of type ListView hence the implementation is very similar. It has two required parameters that are:

  • children: This parameter takes the List of children widgets.

  • onReorder(int oldIndex, int newIndex): This callback function has two fields, oldIndex and newIndex of type integer. After that, we can interchange using the widgets on that index.

ReorderableListView(
  children: _items,
  onReorder: (oldIndex, newIndex) {},
),
Each widget that is the child of ReorderableListView must have a key required for reordering.



Example

In the following example, we have generated a list of widgets and then used a random colour.

Code

class ReorderableListViewTutorial extends StatefulWidget {
  const ReorderableListViewTutorial({Key? key}) : super(key: key);

  @override
  _ReorderableListViewTutorialState createState() =>
      _ReorderableListViewTutorialState();
}

class _ReorderableListViewTutorialState
    extends State<ReorderableListViewTutorial> {
  final List<ListTile> _items = List<ListTile>.generate(
    100,
    (int index) => ListTile(
      key: Key("$index"),
      tileColor: Color(
        (math.Random().nextDouble() * 0xFFFFFF).toInt(),
      ).withOpacity(1.0),
      title: Text("Item $index"),
    ),
  );
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("ReorderableListView Tutorial"),
      ),
      body: ReorderableListView(
        children: _items,
        onReorder: (oldIndex, newIndex) {
          setState(() {
            if (oldIndex < newIndex) {
              newIndex -= 1;
            }
            final ListTile item = _items.removeAt(oldIndex);
            _items.insert(newIndex, item);
          });
        },
      ),
    );
  }
}

Output



Related Posts

See All

The image sharing apps, shopping apps, etc. have image zoom functionality required to see the image in detail. Today, we will learn to implement the same with the help of a widget, InteractiveViewer.

bottom of page