How to Change Order of Items in a ListView in Flutter

I already have couple of Flutter tutorials on ListView widget. Here, I am going to demonstrate a Flutter tutorial where the order of items of a ListView can be changed. What this really means is a user can change the order of item by just dragging and dropping.

Undoubtedly, ListView is one of the most commonly used widgets in Flutter. Here, we are going to use another widget named ReorderableListView . ReorderableListView widget is very appropriate for views with small number of children.

All children of ReorderableListView must have a key. Following is a Flutter example where the order of children can be changed by dragging to up or down position. The onReorder property is used to define action after reordering. Usually, we have to update data on reordering.

import 'package:flutter/material.dart';


class ReorderExample extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Tutorials',
      home: MainScreen()
    );
  }
}

class MainScreen extends StatefulWidget {
  MainScreen({Key key}) : super(key: key);

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

class _MainScreenState extends State<MainScreen> {
  var data= ["Hey","What's","Up","Dude","This","is","a","Flutter","example","got","it"];
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter ListView Example'),
      ),
      body:Container(
       child: ReorderableListView(
         onReorder: (oldIndex,newIndex){
           setState(() {
              _updateItems(oldIndex, newIndex);
           });
         },
         children: [
           for (final item in data)
           Container(
              key: ValueKey(item),
              height: 150,
              color: Colors.white,
              child: Center(child: Text('$item',style: TextStyle(fontSize: 30))),
    )

         ],
  
)
      ),
    );
  }


  void _updateItems(int oldIndex, int newIndex) {
      if(newIndex > oldIndex){
        newIndex -= 1;
      }

      final item = data.removeAt(oldIndex);
      data.insert(newIndex, item);

  }
}

Following is the output of the above Flutter example.

Thank you for reading!

Leave a Comment

Your email address will not be published. Required fields are marked *