Here’s another powerful widget from the Flutter team, as this, in general, can be called GridView widget class which has two constructors (GridView.count
and GridView.extent
).
GridView widget
The GridView widget is another thing borrowed from HTML and the Web. GridView is for displaying a list of widgets when you want them to appear in rows and columns but don’t particularly care which rows and which columns – you just want them to
show up in a grid. To use a GridView
, you’ll set its children property to the list of widgets you want to display and it will create the grid populating across and then wrapping to the next row, resizing its space available until it just fits. And here’s the greatest part, it automatically scrolls!
GridView has two constructors, GridView.extent()
and GridView.count()
.
GridView.extent()
Extent refers to the maximum width of the child. GridView will only let its kids grow to that size. If they try to get bigger, it puts another element on that row and shrinks them all until they just fit across the entire width. Take a look at this example:
Widget build(BuildContext context) { return GridView.extent( maxCrossAxisExtent: 300.0, children: people.map<Widget>((dynamic person) => PersonCard(person)).toList(), ); }
You’ll notice that in the images below, See how the containers resize to something less than 300. GridView decides that it can fit two across in portrait orientation. But when rotated, those two would have resized to something bigger than 300 so it puts three on each row.
GridView.count()
With the GridView.count()
constructor, you specify how many columns you want regardless of orientation. GridView takes care of resizing its contents to fit. In the following example, we’ve told GridView.count() that we want two columns regardless of the orientation and the GridView sizes its children to fit exactly two across.
Widget build(BuildContext context) { return GridView.count( crossAxisCount: 2, children: people.map<Widget>((dynamic person) => PersonCard(person)).toList(), ); }
Now, You can see the difference? GridView.extent()
is probably more useful because when the device is a portrait, maybe you’ll have two columns, but when it goes landscape, you can now fit three columns in and the contents can still fit.