Flutter Reorderable Grid View Easy Explanation [Detailed Example]

flutter reorderable grid view

In this Flutter tutorial, we’ll learn how to use Flutter reorderable grid view. First, we’ll see what a grid view is and why its called reorderable. Then we’ll see how to implement it. We’ll explain its usage with the help of a practical Flutter code example for complete understanding.

Introduction: Flutter Reorderable Grid View

Grid view is used to show a list of items in a grid. The name reorderable specifies that we can change the position of grid items by using drag and drop. This grid view allows us to long press on an item, drag it and drop it in place of any other item.

Let’s now understand this concept by jumping into a detailed Flutter code example. We’ll explain every step in detail so don’t miss out even one step, or else you may face difficulties in understanding the proper implementation of Flutter reorderable grid view.

Implementing Flutter Reorderable Grid View (Example With Proper Explanation)

Follow below steps so you can have a proper understanding of how this reorderable grid view is implemented.

Step 1: Import Package

reorderable_grid_view: ^2.2.5

flutter reorderable grid view package

First, we’ve to import this package in the dependencies block of our pubspec.yaml file’s as shown in the above image. Click here to get the latest version.

import 'package:reorderable_grid_view/reorderable_grid_view.dart';

Then we’ve to write this line in the dart file where we want to use the reorderable grid view.

Step 2: Create a List of Data

For every item, we’ve to provide a unique value key so its better to create a list of items and use that data to assign unique key to each item. For demonstration, we’ve used a simple Dart list of strings. See below:

List<String> listData = [
      'Item 1',
      'Item 2',
      'Item 3',
      'Item 4',
      'Item 5',
      'Item 6',
      'Item 7',
      'Item 8',
      'Item 9',
      'Item 10',
    ];
You can use a list of maps as well. Click here to learn about creating list of maps in detail. In order to make this tutorial simple, we’ve specified a simple list.

Step 3: Create A Flutter Reorderable Grid View

ReorderableGridView.count()

We’ll be using the grid view count in our example. It has two required constructors. These are:

  1. Cross Axis Count
  2. On Reorder

Cross Axis Count

Cross axis count specifies the number of columns. It takes an integer value only. See below:

 crossAxisCount: 2

On Reorder

On reorder is used to update the order of items. See below:

onReorder: (oldIndex, newIndex) {
        setState(() {
          var val = listData.removeAt(oldIndex);
          listData.insert(newIndex, val);
        });
      }

We can see that it takes a function which has two parameters. First one(old index) stores the index value of item which will be dragged and the second one(new index) stores the index value of the item on which the picked item will be dropped.

We’ve created a variable and have used the removeAt() method of list which will remove the item that has been picked/dragged from the list and then store its value inside that variable.

Then we’ve used the insert method of list which will insert the dragged item in its new specified position in list.

Children

We also have to specify items inside the reorderable grid view. For that, we’ve to use the children constructor which takes a list of Flutter widgets. See below code:

children: [
     for (int i = 0; i < listData.length; i++)
          Container(
            margin: EdgeInsets.all(5),
            key: ValueKey(listData[i]),
            color: Colors.blue.shade900,
            alignment: Alignment.center,
            child: Text(
              listData[i],
              style: TextStyle(
                  color: Colors.white,
                  fontWeight: FontWeight.w500,
                  fontSize: 20),
            ),
          )
      ]

We’ve specified a Flutter for loop with a range of list(above specified list) length.

We’ve used a Flutter container widget and have passed a Flutter text widget to it as its child. We’ve displayed the data of list using this text widget.

Unique Key For Each Item

key: ValueKey(listData[i])

We must give a unique key to each item of Flutter reorderable grid view. Also make sure that the key constructor of top most widget of children must be used. In our case, its a container so we’ve used its key constructor. If its wrapped with any other widget like gesture detector, text, container etc. then use the key constructor of that specific widget.

We’ve passed value key to it. Now for its argument, we’ve passed the data of list. Its not necessary to use the same data. What’s necessary is that the data must be in string and unique for each item. We can use the index value of for loop as well like ValueKey(i.toString()).

Let’s now test it. For demonstration, we’ll long press on one item so it’s picked. Then we’ll drag and drop it on some other position. See below images:

flutter reorderable grid view

flutter reorderable grid view count

 

reorderable grid view flutter

So this is how we can properly make use of Flutter reorderable grid view. Your task is to try other constructors of it and share your experience with us. We’d love to see it.

We’ll be super delighted to answer all your questions related to Flutter reorderable grid view.

The complete source code of custom Flutter reorderable grid view is given in the below block.

Beautiful Flutter Reorderable Grid View Source Code

import 'package:flutter/material.dart';
import 'package:reorderable_grid_view/reorderable_grid_view.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        debugShowCheckedModeBanner: false, home: RichTextScreen());
  }
}
class RichTextScreen extends StatefulWidget {
  @override
  State<RichTextScreen> createState() => _RichTextScreenState();
}
class _RichTextScreenState extends State<RichTextScreen> {

  List<String> listData = [
    'Item 1',
    'Item 2',
    'Item 3',
    'Item 4',
    'Item 5',
    'Item 6',
    'Item 7',
    'Item 8',
    'Item 9',
    'Item 10',
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(

        body: ReorderableGridView.count(
      crossAxisCount: 2,
      childAspectRatio: 1.5, // child aspect ratio specifies the width/height of grid
      children: [
        for (int i = 0; i < listData.length; i++)
          Container(
            margin: EdgeInsets.all(5),
            key: ValueKey(listData[i]),
            color: Colors.blue.shade900,
            alignment: Alignment.center,
            child: Text(
              listData[i],
              style: TextStyle(
                  color: Colors.white,
                  fontWeight: FontWeight.w500,
                  fontSize: 20),
            ),
          )
      ],
      onReorder: (oldIndex, newIndex) {
        setState(() {
          var val = listData.removeAt(oldIndex);
          listData.insert(newIndex, val);
        });
      },
    ));
  }
}

Conclusion

In conclusion, hope you now have a proper practical understanding of how to make use of Flutter reorderable grid view. Do feel free to use the comment section in order to share your valuable feedback with us.

We’d be very glad to see you visit our other tutorials on Flutter app development and Python programming. Thank you for reading this article.

Leave a Comment

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