Flutter GridView: A Quick Overview 2023

Flutter GridView Main

Apps and websites often display data in the grid view. You may have seen the menu on some mobiles or an image gallery on websites where elements are arranged across rows and columns. To implement such an arrangement of items in mobile apps, there is a Flutter GridView widget.  

GridView widget lists components in a grid layout. It lets developers create scrolling interface grids that can be easily customized to meet their needs. Read on to learn how to add grids to your next Flutter application.

What is Flutter GridView and Why Use it in Your Apps?

As stated before, GridView is a Flutter widget that arranges items as a 2D array within rows and columns. Unlike lists that add items in a single direction, grids, like tables, render data vertically and horizontally. 

Flutter GridView Layout

Here is the code snippet to run GridView in your app:

import 'package:flutter/widgets.dart';

GridView.builder(

  gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(

    crossAxisCount: 2,

  ),

 children: [

    Item1, 

    Item 2,

    Item 3,

    Item 4,

  ],

)

You can define the number of columns in the gridDelegate property that will determine how items are arranged in the grid. 

Here I want to clarify one concept regarding main and cross axes. As you scroll up and down, the main axis is in the vertical direction, whereas the cross axis is horizontal. The grid layout arranges items on the main and cross axes. You can change the scrolling direction with the scrollDirection property. 

GridView main axis

Now coming back to the example I was discussing above, if you change the value of crossAxixCount to 4, it will place items in four columns instead of two. 

You might wonder, what advantages would you gain by placing elements in the grid using the widget?

The grid format is a time-honored UX design that offers a user-friendly experience. With GridView, you can comfortably display images, videos, and other components to satisfy the specific need of the app. 

Another notable benefit, and perhaps the most significant, is the level of flexibility that it imparts to the design. You can define the number of columns, and the items will automatically take up the available space on the screen. Each time you alter the number of columns, the layout will change accordingly. 

GridView is also capable of handling large amounts of data. By using lazy loading, the widget only loads the currently visible items on the screen. This will improve performance and reduce memory usage.

Additionally, you may be interested in reading: How to Add Space Between Rows? Easy Way to Do It.

GridView Widget Properties

Before we start implementing the Flutter GridView widget, let us first look at its common properties:

crossAxisSpacing

This property allows you to add space between elements on the cross-axis. In a vertical scroll direction, the space appears on the horizontal axis.

GridView(

  gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(

      crossAxisCount: 5, 

      crossAxisSpacing: 16),

  children: [

   Item 1,

   Item 2,

   Item 3,

)

mainAxisSpacing

The mainAxixSpacing property adds the space in the scroll direction, whether it is in the vertical or horizontal direction. 

GridView(

  gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(

      crossAxisCount: 5, 

      mainAxisSpacing: 16),

  children: [

   Item 1,

   Item 2,

   Item 3,

)

scrollDirection

As stated before, the direction of scrolling can be set with this property. You can change the scroll direction from up down to left-right. 

GridView(

  gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(

    crossAxisCount: 5,

  ),

  scrollDirection: Axis.vertical,

  children: [

   Item 1,

   Item 2,

   Item 3,

  ],

)

How to Implement Flutter GridView in Your App

GridView class helps to arrange the components nicely in the grid. Here is how you can use the FlutterGridView:

Implementation of flutter GridView in your app:

class HomePage extends StatefulWidget {

  const HomePage({Key? key}) : super(key: key);

  @override

  State<HomePage> createState() => _HomePageState();

}

class _HomePageState extends State<HomePage> {

  @override

  Widget build(BuildContext context) {

    return Scaffold(

      appBar: AppBar(

        title: const Text('Grid View'),

      ),

      body: GridView(

        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(

          crossAxisCount: 2,

          crossAxisSpacing: 10,

          mainAxisSpacing: 10,

        ),

        padding: const EdgeInsets.all(10),

        children: [

          Container(

            decoration: BoxDecoration(

              border: Border.all(color: Colors.black54),

            ),

          ),

          Container(

            decoration: BoxDecoration(

              border: Border.all(color: Colors.black54),

            ),

          ),

          Container(

            decoration: BoxDecoration(

              border: Border.all(color: Colors.black54),

            ),

          ),

        ],

      ),

    );

  }

}

You can also use GridView.builder to add grids in your app. Here is how you can incorporate it:

const HomePage({Key? key}) : super(key: key);

  @override

  State<HomePage> createState() => _HomePageState();

}

class _HomePageState extends State<HomePage> {

  @override

  Widget build(BuildContext context) {

    return Scaffold(

      appBar: AppBar(

        title: const Text('Grid View'),

      ),

      body: GridView.builder(

        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(

          crossAxisCount: 3,

          crossAxisSpacing: 10,

          mainAxisSpacing: 10,

        ),

        padding: const EdgeInsets.all(10),

        itemCount: 10,

        itemBuilder: (BuildContext context, int index) {

          return Container(

            decoration: BoxDecoration(

              border: Border.all(color: Colors.black),

            ),

            child: Center(child: Text(index.toString())),

          );

        },

      ),

    );

  }

}

What is GridTile and How to Use it With Flutter GridView?

By using GridTile, we can create tiles that contain rich content (text, images, and icons). Tiles usually contain both visual content (such as an image) and a GridTileBar in the header or footer.

GridTile in Flutter

Implementation:

class HomePage extends StatefulWidget {

  const HomePage({Key? key}) : super(key: key);

  @override

  State<HomePage> createState() => _HomePageState();

}

class _HomePageState extends State<HomePage> {

  @override

  Widget build(BuildContext context) {

    return Scaffold(

      appBar: AppBar(

        title: const Text('Grid View'),

      ),

      body: GridView(

        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(

          crossAxisCount: 2,

          crossAxisSpacing: 10,

          mainAxisSpacing: 10,

        ),

        padding: const EdgeInsets.all(10),

        children: const [

          GridTile(

            child: Center(child: Text('Item 1')),

          ),

          GridTile(

            child: Center(child: Text('Item 2')),

          ),

          GridTile(

            child: Center(child: Text('Item 3')),

          ),

          GridTile(

            child: Center(child: Text('Item 4')),

          ),

        ],

      ),

    );

  }

}

GridView.builder for Displaying an Infinite Number of Items

In some instances, you may have to show a large number of items in the grid layout. For this purpose, you need GridView.builder() constructor. 

Implementation

class HomePage extends StatefulWidget {

  const HomePage({Key? key}) : super(key: key);

  @override

  State<HomePage> createState() => _HomePageState();

}

class _HomePageState extends State<HomePage> {

  @override

  Widget build(BuildContext context) {

    return Scaffold(

      appBar: AppBar(

        title: const Text('Grid View'),

      ),

      body: GridView.builder(

        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(

          crossAxisCount: 3,

          crossAxisSpacing: 10,

          mainAxisSpacing: 10,

        ),

        padding: const EdgeInsets.all(10),

        itemBuilder: (BuildContext context, int index) {

          return Container(

            decoration: BoxDecoration(

              border: Border.all(color: Colors.black),

            ),

            child: Center(child: Text(index.toString())),

          );

        },

      ),

    );

  }

}

How to Display Grids on Larger Screens 

Due to recent developments in Flutter, you can now create apps for desktop and web. To maintain your app’s user-friendliness, you should ensure that it is fully responsive on larger screens. 

You can make the grid layout responsive by implementing this code. 

class HomePage extends StatefulWidget {

  const HomePage({Key? key}) : super(key: key);

  @override

  State<HomePage> createState() => _HomePageState();

}

class _HomePageState extends State<HomePage> {

  @override

  Widget build(BuildContext context) {

    return LayoutBuilder(builder: (context, constraints) {

      final deviceWidth = constraints.maxWidth;

      late int crossAxisCount;

      if (deviceWidth <= 480) {

        /// Mobile

        crossAxisCount = 3;

      } else if (deviceWidth > 480 && deviceWidth <= 700) {

        /// Tab

        crossAxisCount = 5;

      } else {

        /// Web or desktop

        crossAxisCount = 7;

      }

      return Scaffold(

        appBar: AppBar(

          title: const Text('Grid View'),

        ),

        body: GridView.builder(

          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(

            crossAxisCount: crossAxisCount,

            crossAxisSpacing: 10,

            mainAxisSpacing: 10,

          ),

          itemCount: 20,

          padding: const EdgeInsets.all(10),

          itemBuilder: (BuildContext context, int index) {

            return Container(

              decoration: BoxDecoration(

                border: Border.all(color: Colors.black),

              ),

              child: Center(child: Text(index.toString())),

            );

          },

        ),

      );

    });

  }

}

You can also add GridView with maxcrossAxisExtent in the responsiveness section like this:

class HomePage extends StatefulWidget {

  const HomePage({Key? key}) : super(key: key);

  @override

  State<HomePage> createState() => _HomePageState();

}

class _HomePageState extends State<HomePage> {

  @override

  Widget build(BuildContext context) {

    return Scaffold(

      appBar: AppBar(

        title: const Text('Grid View'),

      ),

      body: GridView.builder(

        gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent(

          crossAxisSpacing: 10,

          mainAxisSpacing: 10,

          maxCrossAxisExtent: 300,

        ),

        itemCount: 20,

        padding: const EdgeInsets.all(10),

        itemBuilder: (BuildContext context, int index) {

          return Container(

            decoration: BoxDecoration(

              border: Border.all(color: Colors.black),

            ),

            child: Center(child: Text(index.toString())),

          );

        },

      ),

    );

  }

}

Looking for Flutter Developer Agency?

If you have an idea and want to translate it into a mobile app, hire a Flutter Developer. You get the product exactly how you want it with the help of our experienced and dedicated developers.

Here are some more articles from FlutterDesk:

  1. Read this blog if you want to remove debug banner in Flutter
  2. You can set the Flutter drawer header height by the steps mentioned in this article. 
  3. You can also highlight specific content with the custom cards in Flutter

Leave a Comment

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

Share Post On

Haroon Ashraf

Flutter Developer

Detail-oriented full-stack engineer with 9+ years of industry experience. He’s been working on Flutter since 2018 and has delivered 30+ successful projects.He has experience in project management Trello, Github, Jira…..

Flutter
Xcode
IOS-Swift
Full Stack
Bloc/Cubit
Nodejs

Experience

Availability

9 years

Full-Time

Translate »