Search code examples
flutterdartflutter-layout

How to use Reorderable Listview by drag and drop it by leading icon?


Hi I want ReorderableListView in my code But by default ReorderableListView was reordered by drag and dropping the icon in the trailing,

But in my case I want to reorder the items by using leading icon. I don't know how to achieve it please help.


Solution

  • You can use ReorderableDragStartListener that will recognize the start of a drag on the wrapped widget by a PointerDownEvent, and immediately initiate dragging the wrapped item to a new location in a reorderable list

    according to example of buildDefaultDragHandles you can use:

    class ReorderList extends StatefulWidget {
      const ReorderList({Key? key}) : super(key: key);
    
      @override
      State<ReorderList> createState() => _ReorderListState();
    }
    
    class _ReorderListState extends State<ReorderList> {
      final List<int> _items = List<int>.generate(50, (int index) => index);
    
      @override
      Widget build(BuildContext context) {
        return ReorderableListView(
          buildDefaultDragHandles: false, //<-- set this to false to avoid build draghandle
          children: <Widget>[
            for (int index = 0; index < _items.length; index++)
              ListTile(
                key: Key(index.toString()), //<-- use key
                title: Text(_items[index].toString()),
                leading: ReorderableDragStartListener( //<-- add this to leading
                  index: index,
                  child: Icon(Icons.tiktok),
                ),
              )
          ],
          onReorder: (int oldIndex, int newIndex) {
            setState(() {
              if (oldIndex < newIndex) {
                newIndex -= 1;
              }
              final int item = _items.removeAt(oldIndex);
              _items.insert(newIndex, item);
            });
          },
        );
      }
    }
    

    result be like:

    result