skip to Main Content

I want to create a responsive GridView() but just about everything I find discusses ways to do so that involve adjusting the number of cells in the grid’s rows and columns. That’s not what I’m trying to do; I’m using a SliverGridDelegateWithFixedCrossAxisCount().

How do you make a GridView() widget that’s responsive, with

  • a fixed arrangement of columns and rows. As the viewport width and height change, I want the cell sizes to change (rather than the arrangement of rows and columns), and
  • cells that appear square, i.e., the childAspectRatio is 1?

My code looks like this:

return GridView.builder(
      physics: const NeverScrollableScrollPhysics(),
      gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 5,
        mainAxisSpacing: 4,
        crossAxisSpacing: 4,
        childAspectRatio: 1,
      ),
      itemBuilder: (context, index) {
        return Container(
          height: cellSize,
          decoration: BoxDecoration(
            border: Border.all(
              color: Theme.of(context).primaryColorLight,
            ),
            color: Colors.white,
          ),
          child: Tile(index: index),
        );
      },
      padding: const EdgeInsets.fromLTRB(36, 20, 36, 20),
      itemCount: 30,
    );

Tile() is a custom widget but it’s a Container(). And cellSize does a MediaQuery.of(context) to figure out whether the view’s height or width is smaller and select a size to fit.

2

Answers


  1. Chosen as BEST ANSWER

    I spent a lot of time trying to figure this out and, in the end, simply replaced the GridView with rows and columns of Tile objects.


  2. The default childAspectRatio is 1, you can change the item size from this.

       childAspectRatio: itemWidth/itemHeight,
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search