Flutter 流式布局组件
简述
类似于Android中的FlexboxLayout布局。
Wrap
spacing: 主轴间距。
runSpacing: 纵轴间距。
direction: 布局方向。
alignment: 主轴对齐方式。
- Axis.horizonta:水平方向。
- Axis.vertical:垂直方向。
alignment:主轴堆起方式。
crossAxisAlignment: 纵轴对齐方式。
runAlignment :纵轴方向,每一行的对齐方式
Wrap(
//主轴间距
spacing: 8,
//纵轴间距
runSpacing: 4,
//布局方向
direction: Axis.horizontal,
children: List.generate(
13,
(index) {
double w = 50.0 + 10 * index;
return Container(
width: w,
height: 50,
color: Colors.red,
alignment: Alignment.center,
child: Text("$index"),
);
},
),
)
Flow
Flow相比Wrap更加复杂,一般情况优先使用Wrap,如果需要一些自定义布局或性能要求高时可以使用Flow。
Flow(
delegate: MyFlowDelegate(margin: const EdgeInsets.all(10)),
children: List.generate(
13,
(index) {
double w = 50.0 + 10 * index;
return Container(
width: w,
height: 50,
color: Colors.red,
alignment: Alignment.center,
child: Text("$index"),
);
},
),
)
class MyFlowDelegate extends FlowDelegate {
EdgeInsets margin;
double width = 0;
double height = 0;
MyFlowDelegate({this.margin = EdgeInsets.zero});
@override
void paintChildren(FlowPaintingContext context) {
var x = margin.left;
var y = margin.top;
for (int i = 0; i < context.childCount; i++) {
var width = context.getChildSize(i)!.width + x + margin.right;
if (width < context.size.width) {
context.paintChild(i, transform: Matrix4.translationValues(x, y, 0));
x = width + margin.left;
} else {
x = margin.left;
y += context.getChildSize(i)!.height + margin.top + margin.bottom;
context.paintChild(i, transform: Matrix4.translationValues(x, y, 0));
x += context.getChildSize(i)!.width + margin.left + margin.right;
}
}
}
@override
bool shouldRepaint(covariant FlowDelegate oldDelegate) {
return this != oldDelegate;
}
@override
Size getSize(BoxConstraints constraints) {
return const Size(double.infinity, 200);
}
}