首先在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)
还有一种方式就是直接重写girdview的源码,这个也是我在网上找大神提供的代码,非常好用,废话不多说直接上代码
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<Widget> 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<Widget> 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);
}
}
}
重写后的代码使用 文章来源:https://www.toymoban.com/news/detail-688653.html
OptionGridView(
itemCount: 12,
rowCount: 3,
mainAxisSpacing: 10,
crossAxisSpacing: 10,
itemBuilder: _initlistdata,
),
上述就是修改GridView展示的全部代码了,喜欢的留个赞吧 文章来源地址https://www.toymoban.com/news/detail-688653.html
到了这里,关于Flutter GridView 自定义宽高的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!