In Flutter, when it comes to displaying a list of items in a grid layout, the GridView
widget is often used. However, one common issue developers face while using GridView
is setting custom heights for widgets within it. In this blog post, we will explore how to set custom heights for widgets inside a GridView
in Flutter.
The Problem with GridView’s Default Behavior
When you use the GridView.count
widget in Flutter, by default, it resizes your items to fit the available space. This means that if you have widgets of varying heights and widths, they might not display as expected within a grid layout.
The Key to Customizing GridView’s Behavior: childAspectRatio
The key to customizing GridView
‘s behavior lies in the childAspectRatio
property. This value determines how the grid layout is laid out based on the size of your items. To get the desired aspect ratio, you need to set it to the (itemWidth / itemHeight).
Setting Custom Height for Widgets inside GridView
To demonstrate how this works, let’s consider an example code snippet.
class MyHomePage extends StatefulWidget { MyHomePage({Key key, this.title}) : super(key: key); final String title; @override _MyHomePageState createState() => new _MyHomePageState(); } class _MyHomePageState extends State{ List widgetList = ['A', 'B', 'C']; @override Widget build(BuildContext context) { var size = MediaQuery.of(context).size; /*24 is for notification bar on Android*/ final double itemHeight = (size.height - kToolbarHeight - 24) / 2; final double itemWidth = size.width / 2; return new Scaffold( appBar: new AppBar( title: new Text(widget.title), ), body: new Container( child: new GridView.count( crossAxisCount: 2, childAspectRatio: (itemWidth / itemHeight), controller: new ScrollController(keepScrollOffset: false), shrinkWrap: true, scrollDirection: Axis.vertical, children: widgetList.map((String value) { return new Container( color: Colors.green, margin: new EdgeInsets.all(1.0), child: new Center( child: new Text( value, style: new TextStyle( fontSize: 50.0, color: Colors.white, ), ), ), ); }).toList(), ), ), ); } }
A Simpler Approach to Setting Custom Height for GridView Widgets
However, there’s a simpler way to achieve this without calculating the itemHeight
. By setting childAspectRatio
directly, you can customize the height of your widgets inside the grid view.
return GridView.count( crossAxisCount: 2, childAspectRatio: (1 / .4), shrinkWrap: true, children: List.generate(6, (index) { return Padding( padding: const EdgeInsets.all(10.0), child: Container( color: Colors.grey[600], child: Row( children: [ ], ), ), ); }), );
Conclusion
In this blog post, we’ve explored the key to setting custom heights for widgets inside a GridView
in Flutter. By using the childAspectRatio
property and understanding how it works, you can easily customize your grid layouts to suit your needs.