GridView Class Tutorial

GridView is a 2-d scrollable list of widgets. We can display items in the form of a grid. The grid can have any number of columns and rows.

Create a GridView

To create a simple GridView in Flutter, we will use the following syntax:-

GridView(
  gridDelegate: grid_delegate,
  children: [],
),

The gridDelegate field asks for a delegate to control the view within the GridView. Suppose we want to have 3 columns or 2 columns, depending on the delegate, the GridView will show the respective number of columns.

Here is an example where we are creating a GridView with a total of 8 container widgets with different colours. The number of columns will be 2, so we will pass a grid delegate with a fixed cross-axis count of value equals 2.

Import the math class to generate the random colour.

GridView(
  gridDelegate:
      const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
  children: [
    for (var i = 0; i < 8; i++)
      Container(
        width: MediaQuery.of(context).size.width / 2.3,
        height: MediaQuery.of(context).size.width / 2.3,
        color: Color((Random().nextDouble() * 0xFFFFFF).toInt())
            .withOpacity(1.0),
        child: Text((i + 1).toString()),
      )
  ],
),

GridView.count is another type of GridView where we don't need to pass the delegate. Here is a similar example but without a grid delegate. Instead, it directly asks for the number of columns as crossAxisCount.

GridView.count(
  crossAxisCount: 3,
  children: [
    for (var i = 0; i < 18; i++)
      Container(
        width: MediaQuery.of(context).size.width / 2.3,
        height: MediaQuery.of(context).size.width / 2.3,
        color: Color((Random().nextDouble() * 0xFFFFFF).toInt())
            .withOpacity(1.0),
        child: Center(
            child: Text(
          (i + 1).toString(),
          style: const TextStyle(
            fontSize: 32.0,
            fontWeight: FontWeight.w600,
          ),
        )),
      )
  ],
),

Output

Did you find this article valuable?

Support All About Flutter | Flutter and Dart by becoming a sponsor. Any amount is appreciated!