GridView which automatically sets row height to the tallest grid item

Viewed 781

The title is a simplified version of what I'm trying to achieve: a GridView which automatically sets row height based on a prototype grid item that I supply. The prototype item is a tallest possible item, for example if the grid items contain text, the prototype would contain a longest possible text.

A possible workaround is a ListView in which each row is wrapped in an IntrinsicHeight widget. But:

  • Row height is not necessarily uniform like in a GridView.
  • IntrinsicHeight is inefficient per the documentation. Not sure how much though, perhaps it's negligible for simple layouts. Ideally this "compute intrinsic height" operation would only be called for the one prototype row.
2 Answers

For setting custom row heights depending upon the item that is fed into the grid item you can consider using this flutter_staggered_grid_view plugin.

It provides different widgets for both normal grids and sliver grids and will take care of the random size of input. So whatever size of widget you feed to the grid it'll take the size of the item

As far as I understand, you want to dynamically set size for GridView item. There are two ways, calculate it manually and set every time based on your contents, or to use SliverGridDelegateWithMaxCrossAxisExtent. So in your GridView.builder you can add following attribute:

gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
                        maxCrossAxisExtent:
                            200.0, // maximum size of item (on small screens 1 item per row, on bigger as many as can fit with 200.0 px width)
                        childAspectRatio: 5 / 6,
                        crossAxisSpacing: 20,
                        mainAxisSpacing: 20,
                      ),

It gives you access to extra tools for managing the GridView items keeping the aspect ratio, it also has maximum size that it should not exceed

Related