首先在children获取控件中进行高度设置,是不生效的。因为系统默认宽高比属性childAspectRatio控制,默认宽高比1:1。 先介绍一下系统自带的方式调整大小,但是这个不能控制他的宽高固定是多少,
GridView.builder( padding: EdgeInsets.fromLTRB(20, 20, 20, 0), itemCount: 10, gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( //一行多少个 crossAxisCount: 2, crossAxisSpacing: 20, //设置列间距 mainAxisSpacing: 10, //设置行间距 ), itemBuilder: _initlistdata)
import 'package:flutter/cupertino.dart';import 'package:flutter/material.dart';/// 多按钮布局,可用于单行及多行按钮布局/// 平均分配每个按钮宽度,自适应每行最高高度/// 可添加按钮之间的间距,可添加多行之间的间距class OptionGridView extends StatelessWidget { final int itemCount; final int rowCount; final int columnCount; final double mainAxisSpacing; final double crossAxisSpacing; final EdgeInsetsGeometry? padding; final IndexedWidgetBuilder itemBuilder; /// [itemCount] 按钮总个数 /// [rowCount] 每行按钮个数 /// [mainAxisSpacing] 行间距 /// [crossAxisSpacing] 按钮间距 OptionGridView({ Key? key, required this.itemCount, required this.rowCount, this.mainAxisSpacing = 0.0, this.crossAxisSpacing = 0.0, this.padding = const EdgeInsets.all(0), required this.itemBuilder, }) : assert(itemCount >= 0), assert(rowCount > 0), columnCount = (itemCount / rowCount).ceil(), assert(mainAxisSpacing >= 0), assert(crossAxisSpacing >= 0), super(key: key); @override Widget build(BuildContext context) { return ListView.separated( itemCount: columnCount, padding: padding, physics: const NeverScrollableScrollPhysics(), shrinkWrap: true, controller: ScrollController(keepScrollOffset: false), separatorBuilder: (context, index) => SizedBox(height: mainAxisSpacing), itemBuilder: (context, index) => buildRow(context, index), ); } Widget buildRow(BuildContext context, int index) { if (index < columnCount - 1) { List row = []; for (int i = 0; i < rowCount; i++) { row.add(Expanded( flex: 1, child: itemBuilder(context, i + index * rowCount), )); if (crossAxisSpacing > 0.0 && i < rowCount - 1) { row.add(SizedBox(width: crossAxisSpacing)); } } return Row(crossAxisAlignment: CrossAxisAlignment.start, children: row); } else { // 最后一行 List row = []; for (int i = 0; i < rowCount; i++) { int currentIndex = i + index * rowCount; if (currentIndex < itemCount) { row.add(Expanded( flex: 1, child: itemBuilder(context, i + index * rowCount), )); if (crossAxisSpacing > 0.0 && i < rowCount - 1) { row.add(SizedBox(width: crossAxisSpacing)); } } else { row.add(const Expanded(flex: 1, child: SizedBox())); } } return Row(crossAxisAlignment: CrossAxisAlignment.start, children: row); } }}
重写后的代码使用
OptionGridView( itemCount: 12, rowCount: 3, mainAxisSpacing: 10, crossAxisSpacing: 10, itemBuilder: _initlistdata, ),
上述就是修改GridView展示的全部代码了,喜欢的留个赞吧
来源地址:https://blog.csdn.net/as425017946/article/details/131395380
--结束END--
本文标题: Flutter GridView 自定义宽高
本文链接: https://lsjlt.com/news/423394.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-01-21
2023-10-28
2023-10-28
2023-10-27
2023-10-27
2023-10-27
2023-10-27
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0