Search code examples
flutterdartgrid-layout

How to align text and image in a SliverGrid in Flutter?


I am using the SliverGrid feature to build my gridView. I trying to have the text placed below the image but the text isn't aligning with the image and its showing a Bottom Overflowed error. This is the code:

SliverPadding(
          padding: const EdgeInsets.only(left: 8, right: 8),
          sliver: SliverGrid(
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 3,
              crossAxisSpacing: 20,
              mainAxisSpacing: 20,
            ),
            delegate: SliverChildBuilderDelegate(
              (BuildContext context, int i) {
                return GestureDetector(
                  onTap: () {},
                  child: Column(
                    children: <Widget>[
                      GridTile(
                        child: Image.network(
                          'https://images.unsplash.com/photo-1562176566-73c303ac1617?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80',
                          fit: BoxFit.cover,
                        ),
                      ),
                      Text(
                        'Sammy the Pup',
                        style: khomeStyle.copyWith(
                            color: kOrange, fontSize: 14),
                      ),
                    ],
                  ),
                );
              },
              childCount: 200,
            ),
          ),
        ),

And this is what the gridview looks like(Output of the above): enter image description here

And this is what I want to achieve:

enter image description here


Solution

  • The height of GridView is determined by the AspectRatio

    SliverGridDelegateWithFixedCrossAxisCount(
                mainAxisSpacing: 5.0,
                crossAxisSpacing: 5.0,
                crossAxisCount: 2,
                childAspectRatio: 1 / 1,<---
              ),
    

    As the AspectRatio gets smaller the height gets larger and as the ratio gets larger the heights gets smaller