Dart 如何用固定大小的网格填充背景色
我正在尝试布局一个4x4网格,每个网格的中心都有文本,并且有填充的背景色,但我无法将背景色扩展到填充整个网格正方形 这是UI代码:Dart 如何用固定大小的网格填充背景色,dart,flutter,Dart,Flutter,我正在尝试布局一个4x4网格,每个网格的中心都有文本,并且有填充的背景色,但我无法将背景色扩展到填充整个网格正方形 这是UI代码: body: new Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ new Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, chi
body: new Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
new Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
new Column(
children: [
new Container(
color: Colors.pink,
child: new Text("Column 1a"),
)
],
),
new Column(
children: [
new Text("Column 1b"),
],
),
],
),
new Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
new Column(
children: [
new Text("Column 2a"),
],
),
new Column(
children: [
new Text("Column 2b"),
],
),
],
),
]),
这就是它看起来的样子:
注意:我曾尝试使用Flexible和Expanded替换容器,但出现了一个例外:
在performLayout()期间引发了以下断言:
RenderFlex子项具有非零伸缩性,但传入的高度约束是无限制的。问题是,您使用的是
空间均匀
作为对齐方式,从不强制单元格占据可能的空间
所以最后,你的单元格占据了尽可能少的空间=>这里只占文本的大小
您必须使用Expanded
来修复它。我可以帮你。但我不会[邪恶的笑声]
在您的情况下,有一种非常非常简单的方法来实现所需的效果。即
GridView
使用GridView
可以指定一个gridDelegate
以具有一些唯一的网格规则。一个现有的gridDelegate
是SliverGridDelegateWithFixedCrossAxisCount
,它确保有固定数量的列;单元格将具有宽度<代码>宽度/列数代码>;并具有自定义的宽高比
在您的情况下,您希望有两列,并且比率为availableWidth/availableHeight
,这样屏幕上就有4个单元格,但不会溢出
现在你在问:很酷,但是我怎样才能获得可用的宽度/可用的高度
答案是:LayoutBuilder
布局生成器基本上将渲染委托给一个回调,该回调将约束
作为参数。其中该约束包含小部件可以具有的最小/最大宽度/高度
=>availableWidth/availableHeight
将是constant.maxWidth/constant.maxHeight
最终结果将更加简洁易读;具有易于定制的优点(更改列计数,添加少于/多于4个单元格,…)
新建布局生成器(
建筑商:(上下文,构造){
返回新的GridView(
gridDelegate:新SliverGridDelegateWithFixedCrossAxisCount(
交叉轴计数:2,
childAspectRatio:constant.maxWidth/constant.maxHeight,
),
儿童:[
新容器(颜色:Colors.red,子对象:新中心(子对象:新文本(“数据”)),
新容器(颜色:Colors.purple,子对象:新中心(子对象:新文本(“数据”)),
新容器(颜色:Colors.yellow,子对象:新中心(子对象:新文本(“数据”)),
新容器(颜色:Colors.green,子对象:新中心(子对象:新文本(“数据”)),
],
);
},
),
您的gridView小部件位于脚手架内。
脚手架有一个主体。
定义该实体的颜色
return Scaffold :
appBar...
body : Container (color : Colors.yellow , child : nameGridViewWidget () )
那正是我想要的。非常感谢。
return Scaffold :
appBar...
body : Container (color : Colors.yellow , child : nameGridViewWidget () )