前言
目前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);
})
)
);
創(chuàng)建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 實現(xiàn)
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左邊加上子控件寬度小于屏幕寬度 則繼續(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;
}
}
UI效果顯示