前言
目前Flutter常见的布局方式主要有4种:1、线性布局 2、流式布局 3、弹性布局 4、层叠布局
今天我们主要介绍流式布局
线性布局
弹性布局
层叠布局
流式布局
我们把超出屏幕显示范围会自动换行的布局称为流式布局
关键字Wrap、Flow
流式布局Wrap关键字
body: Wrap(
direction: Axis.horizontal,
children: [
Container(
margin: EdgeInsets.only(left: 30,top: 30),
width: 100,
height: 100,
color: Colors.red,
child: Text("1",style:TextStyle(
color: Colors.white,
fontSize: 60,
)),
),
Container(
margin: EdgeInsets.only(left: 30,top: 30),
width: 100,
height: 100,
color: Colors.yellow,
child: Text("3",style:TextStyle(
color: Colors.white,
fontSize: 60,
)),
),
Container(
margin: EdgeInsets.only(left: 30,top: 30),
width: 100,
height: 100,
color: Colors.blue,
child: Text("3",style:TextStyle(
color: Colors.white,
fontSize: 60,
)),
),
Container(
margin: EdgeInsets.only(left: 30,top: 30),
width: 100,
height: 100,
color: Colors.blue,
child: Text("4",style:TextStyle(
color: Colors.white,
fontSize: 60,
)),
),
],
)
流式布局Flow关键字
return Scaffold(
appBar: AppBaseBar("流式布局"),
body: Flow(
delegate: MyFlowDelegate(boxSize: 80),
children: List.generate(15, (index){
return Box(index, 80);
})
)
);
创建Box 代码
/*一个正方形*/
Widget Box(index,double boxSize) => Container(
width: boxSize,
height: boxSize,
alignment: Alignment.center,
color: Colors.red,
child: Text(
index.toString(),
style: TextStyle(
color: Colors.white,
fontSize: 50,
fontWeight: FontWeight.bold,
),
),
);
delegate 实现
class MyFlowDelegate extends FlowDelegate {
MyFlowDelegate({this.boxSize});
final boxSize;
@override
void paintChildren(FlowPaintingContext context) {
/*屏幕宽度*/
var screenW = context.size.width;
double padding = 5; //间距
double offsetX = padding; //x坐标
double offsetY = padding; //y坐标
for (int i = 0; i < context.childCount; i++) {
/*如果当前x左边加上子控件宽度小于屏幕宽度 则继续绘制 否则换行*/
if (offsetX + boxSize < screenW) {
/*绘制子控件*/
context.paintChild(I,
transform: Matrix4.translationValues(offsetX, offsetY, 0));
/*更改x坐标*/
offsetX = offsetX + boxSize + padding;
} else {
/*将x坐标重置为margin*/
offsetX = padding;
/*计算y坐标的值*/
offsetY = offsetY + boxSize + padding;
/*绘制子控件*/
context.paintChild(I,
transform: Matrix4.translationValues(offsetX, offsetY, 0));
}
}
}
@override
bool shouldRepaint(FlowDelegate oldDelegate) {
return true;
}
}