Flutter中如何为GridView的Widget设自定义高度?解决设置后仍为方形问题
解决Flutter GridView子Widget强制方形的问题
这个问题我之前也踩过坑!你给Container设置的height之所以没生效,是因为GridView.count默认会给所有子Widget施加1:1的宽高比约束,直接覆盖了你自定义的高度设置😅
问题根源
GridView.count是Flutter提供的快捷构造方法,它默认使用SliverGridDelegateWithFixedCrossAxisCount作为布局代理,其中childAspectRatio参数的默认值是1.0——这个参数代表宽度/高度的比值,1.0就意味着宽高完全相等,所以你的子Widget自然会变成方形。
快速解决方案
只需要在GridView.count中添加childAspectRatio参数,根据你想要的宽高比例调整数值就行。比如你想让子Widget的高度是宽度的1.5倍,那childAspectRatio就设为1/1.5 ≈ 0.67(因为宽/高=0.67 → 高=宽/0.67≈1.5*宽)。
修改后的完整代码如下:
class MyHomePage extends StatefulWidget { MyHomePage({Key key, this.title}) : super(key: key); final String title; @override _MyHomePageState createState() => new _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { List<String> widgetList = ['A', 'B', 'C']; @override Widget build(BuildContext context) { return new Scaffold( appBar: new AppBar( title: new Text(widget.title), ), body: new Container( child: new GridView.count( crossAxisCount: 2, controller: new ScrollController(keepScrollOffset: false), shrinkWrap: true, scrollDirection: Axis.vertical, // 关键:设置宽高比,这里宽是高的0.6倍,让高度大于宽度 childAspectRatio: 0.6, 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(), ), ), ); } }
进阶:自定义每个Item的高度
如果你的需求是每个Item的高度不一样,可以使用GridView.custom配合ConstrainedBox来实现:
GridView.custom( shrinkWrap: true, scrollDirection: Axis.vertical, gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 2, ), childrenDelegate: SliverChildBuilderDelegate( (context, index) { // 为不同索引的Item设置不同高度 double itemHeight = index == 0 ? 250 : 180; return ConstrainedBox( constraints: BoxConstraints( minHeight: itemHeight, maxHeight: itemHeight, ), child: Container( color: Colors.green, margin: const EdgeInsets.all(1.0), child: Center( child: Text( widgetList[index], style: const TextStyle(fontSize: 50.0, color: Colors.white), ), ), ), ); }, childCount: widgetList.length, ), )
这样就能完全控制每个Item的高度啦!
内容的提问来源于stack exchange,提问作者Ajay
相关产品推荐
相关产品推荐

