Flutter ReorderableListView not working, it is not persisting list child

I am using ReorderableListView, it handles the movement but as soon as I leave the touch, it goes back to the original data supplied. Here is the expected output. Can anyone show how to achieve this?

enter image description here

1 answer

  • answered 2019-05-21 12:43 Volleyball

    You can use this code.

    class _HomePageState extends State<HomePage> {
      List<String> _list = List.generate(5, (i) => "${i}");
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(),
          body: ReorderableListView(
            padding: EdgeInsets.symmetric(horizontal: 40),
            children: _list.map((String string) => ListTile(key: Key(_list[_list.indexOf(string)]), title: Text(string))).toList(),
            onReorder: (oldIndex, newIndex) {
              String old = _list[oldIndex];
              if (oldIndex > newIndex) {
                for (int i = oldIndex; i > newIndex; i--) {
                  _list[i] = _list[i - 1];
                }
                _list[newIndex] = old;
              } else {
                for (int i = oldIndex; i < newIndex - 1; i++) {
                  _list[i] = _list[i + 1];
                }
                _list[newIndex - 1] = old;
              }
              setState(() {});
            },
          ),
        );
      }
    }