DEV Community

Cover image for How To Implement GridView Class in Flutter
Usman
Usman

Posted on • Originally published at maxidev.hashnode.dev

How To Implement GridView Class in Flutter

Introduction

In Flutter development we often encounter different forms of designs which require specific elements to help facilitate a better user experience. One of these elements can come in the form of Grids and we need a 'GridView' class to implement that. There are other various widgets in Flutter but we will be talking about the 'GridView' class and its various constructors today.

Prerequisite

To get the most out of this guide, You should have a basic understanding of Flutter and have it installed on your device. If you’re unfamiliar with this I recommend visiting the original Flutter documentation to set up your device. You can also use an online Flutter editor (Flutlab).

Understanding the GridView class

As the name implies the GridView class is usually used when we want to implement a grid-like design. For example, if we want to design the user interface of a chessboard, we have the white and black squares across the whole board, another good example is photos in the gallery. These square boxes are grid-like designs. I will go in-depth on the various methods that are associated with this class and its constructors.  The GridView class has the main GridView builder,  GridView.count, GridView .custom and  GridView.extent. You have to note that there are certain limitations and benefits to each of the constructors, I will be discussing them in the sections below. Let's get into it.

How to use the GridView Class

To utilize the most out of the GridView class, You need to have an idea of the items you intend to display on the screen. You must also be familiar with the terminologies used in this section of the article. Common terms and properties associated with the GridView class are :

1 - itemCount: It determines the total number of items within the grid.

2 - gridDelegate: It plays a pivotal role in defining the layout and appearance of the grid. This takes in two parameters which are :

I.  SliverGridDelegateWithFixedCrossAxisCount: This creates grid layouts with a fixed number of tiles in the cross-axis.

II. SliverGridDelegateWithMaxCrossAxisExtent: This creates grid layouts with tiles that each have a maximum cross-axis extent.

3 - crossAxisCount: This property defines the number of columns (or rows, depending on the scrolling direction) in the grid layout.

4 - mainAxisSpacing: This property defines the spacing between items along the main axis (vertical spacing if the grid scrolls vertically, and horizontal spacing if the grid scrolls horizontally).

5 - maxCrossAxisExtent: This property defines the spacing between items along the cross-axis (horizontal spacing if the grid scrolls vertically, and vertical spacing if the grid scrolls horizontally).

Now it's time to jump into the coding aspect by analyzing each of the constructors under the GridView class below.

How to use GridView.count

GridView.count constructor is a convenient way to create grid layouts with a fixed number of tiles across the cross-axis. It allows you to specify the number of columns in the grid, and Flutter automatically adjusts the layout based on the available space. It is the most basic way to invoke the GridView class and it uses the crossAxisCount parameter.



class GridViewCount extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: GridView.count(
        crossAxisCount: 2,
      children: [
        Padding(
          padding: const EdgeInsets.all(8.0),
          child: Container(
            height: 50,
            width: 50,
            color: Colors.blue,
          ),
        ),
        Padding(
          padding: const EdgeInsets.all(8.0),
          child: Container(
            height: 50,
            width: 50,
            color: Colors.yellow,
          ),
        ),
        Padding(
          padding: const EdgeInsets.all(8.0),
          child: Container(
            height: 50,
            width: 50,
            color: Colors.yellow,
          ),
        ),
        Padding(
          padding: const EdgeInsets.all(8.0),
          child: Container(
            height: 50,
            width: 50,
            color: Colors.blue,
          ),
        )
      ],
    ));
  }
}


Enter fullscreen mode Exit fullscreen mode

Once you run this code in your editor this is going to be the output :

To explain better, we are displaying a grid with four containers (2 blue, 2 yellow), We specified our grid to have two columns by using the crossAxisCount property and added some padding.

Benefits of GridView.count

It allows you to have precise control over the number of columns which in turn allows you to have complete control over the whole layout and it adapts automatically based on the available space, ensuring a responsive design.

Limitations of GridView.count

It is suitable for scenarios where you need a fixed number of columns and it's not advisable to use when you want a more dynamic layout over the design.


How to use GridView.builder

The GridView.builder constructor is a powerful tool that enables you to create dynamic grid layouts in Flutter. It's different from the basic GridView constructor, which requires you to provide a fixed number of items. It's best to use when working with large datasets or data generated on the go.

Components of GridView.builder

  1. itemBuilder Function: This function is responsible for creating separate grid items, It takes two arguments (context, index) and should return a widget representing the content of the item at a given index

  2. itemCount Property: This is a necessary property that specifies the total number of items in the Grid.

  3. scrollDirection : This property is used to set the direction of scrolling the grid items, It can be set to vertical or horizontal.

Here's how to use it :



class GridViewBuilder extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: GridView.builder(
          gridDelegate:
           SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
          itemCount: 32,
          scrollDirection: Axis.vertical,
          itemBuilder: (context, index) {
            return Padding(
              padding: EdgeInsets.all(8.0),
              child: Container(
                height: 20,
                width: 20,
                color: Color(0xff6c5f5f),
                child: Text('My item', textAlign: TextAlign.center),
              ),
            ); 
          }),
        );
      }
    }


Enter fullscreen mode Exit fullscreen mode

Output :

In the code above, You will notice some properties that were added after the GridView.builder constructor was introduced. Properties added were the “ItemCount”, “itemBuilder”, "scrollDirection". Now in our example, we’re using the constructor to create a GridView that has a gridDelegate with a fixed cross-axis count (2 columns), while setting the itemcount to 32 to produce a total of 32 containers as children with some padding and finally we set the scrollDirection to vertical. These new properties introduced are the main components of using the GridView.builder constructor.

Benefits of using GridView.builder

GridView.builder generates items when they are needed and you can work with data sources of varying length without needing to modify the layout code. It provides smooth scrolling even with a significant number of items.


How to use GridView.extent

The  GridView.extent constructor is suitable for producing grid layouts where each size of each grid item is determined by the maximum extent it can occupy along the cross axis. It's mostly useful when you want a specific size for each item regardless of the screen size.  You always have to specify the maximum cross-axis extent.




class GridViewExtent extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: GridView.extent(
        maxCrossAxisExtent: 150,
        children: List.generate(12, (index) {
         return Padding(
          padding: const EdgeInsets.all(8.0),
          child: Container(
            color: Colors.purple,
            child: Center(
              child: Text('Item ${index + 1}'),
            ),
          ),
        );
      }),
    ));
  }
}


Enter fullscreen mode Exit fullscreen mode

Output :

In the example above, We are displaying a grid with a maxCrossAxisExtent of 150, and the grid is to display a list of 12 generated items across the whole layout with some padding on each item.

Benefits of GridView.extent

It ensures each grid has consistent sizes regardless of screen size, layout is automatically managed which makes the interface more responsive.

Limitations of GridView.extent

It is suitable for scenarios where you want a consistent item size, but it may not be the best choice if you need more dynamic control over item generation or layout.


How to use GridView.custom

The GridView.custom constructor is the most flexible one out of all the constructors as it allows you to control every aspect of the widget, making it suitable for complex scenarios where the arrangements need to meet specific requirements.



class GridViewCustom extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return GridView.custom(
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 2,
        mainAxisSpacing: 16.0,
        crossAxisSpacing: 16.0,
      ),
      childrenDelegate: SliverChildBuilderDelegate(
        (BuildContext context, int index) {
          return Container(
            color: Colors.orange,
            child: Center(
              child: Text('Item ${index + 1}'),
            ),
          );
        },
        childCount: 6,
      ),
    );
  }
}


Enter fullscreen mode Exit fullscreen mode

Output :

Benefits of GridView.custom

This constructor allows you to control the layout and is very adaptive when working with a large set of complex data that depends on complex logic such as data manipulation. The constructor also recycles items off the screen for optimal performance.

Limitations of GridView.custom

It is more intricate and complex to set up. It is only used when custom item generation and or complex layouts.

Conclusion

Now that you know the various methods of incorporating the GridView class, the benefits, and the limitations involved, You can begin to apply it in your next project, and fully implement its constructors when needed to optimize your designs and to give a better user experience.

If you enjoyed the article, You can give me a follow on GitHub.

Happy Coding!

Top comments (1)

Collapse
 
mustafa_oo7 profile image
Kornzx_Hub

Thanks