前言
这篇博客主要探讨Flutter布局的相关原理,分为两个大部分,单child容器的布局和多child容器布局。
布局基本法则
一个Widget的布局主要有四个步骤
- 当前Widget从父Widget获取到约束
- 当前Widget向子级Widget传递约束,子级通过约束确定自身大小
- 当前Widget综合子级Widget大小和自身大小确定子级Widget位置
- 当前Widget将尺寸信息传递给父Widget,完成闭环
单child容器
案例分析
比如Center组件,我们按照基本法则进行分析
- Center拿到父Widget的约束,同时确定自己的宽高为最大可取宽高,也就是填充满父Widget
- Center告诉子Widget可以取任意宽高,子Widget根据约束得到尺寸,并告知Center
- Center根据子Widget和自身尺寸确定子Widget位置,也就是居中
- Center将自身尺寸信息传递给父Widget
使用CustomSingleChildLayout模拟Center
单child容器中有一个特殊的容器CustomSingleChildLayout
,可以用来自定义布局,通过它我们可以更清晰的感受布局流程。
首先定义一个继承自SingleChildLayoutDelegate
的类并且实现四个方法
getSize
此方法用于获取自身的大小,方法会将父Widget的约束传递下来,也就是对应第一步
bash
Size getSize(BoxConstraints constraints) {
print("get size: $constraints");
return constraints.biggest;
}
这里取的是constraints.biggest
,也就是填充满父Widget
getConstraintsForChild
为子Widget生成约束,这里minWidth
和minHeight
都设置为0, 表示允许子Widget在父Widget的尺寸范围内可以取任意大小
php
BoxConstraints getConstraintsForChild(BoxConstraints constraints) {
final relaxConstraint = BoxConstraints(
minWidth: 0,
minHeight: 0,
maxWidth: constraints.maxWidth,
maxHeight: constraints.maxHeight);
return relaxConstraint;
}
getPositionForChild
这个方法告知了我们当前Widget的尺寸和子Widget的尺寸,通过这两个尺寸可以很容易得计算出居中的位置
arduino
Offset getPositionForChild(Size size, Size childSize) {
return Offset((size.width - childSize.width) * 0.5,
(size.height - childSize.height) * 0.5);
}
综合在一起
arduino
class CustomCenterDelegate extends SingleChildLayoutDelegate {
final double xFactor;
final double yFactor;
CustomCenterDelegate({this.xFactor = 0, this.yFactor = 0});
// 自己的大小
Size getSize(BoxConstraints constraints) {
print("get size: $constraints");
return constraints.biggest;
}
// 子widgte的约束
BoxConstraints getConstraintsForChild(BoxConstraints constraints) {
final relaxConstraint = BoxConstraints(
minWidth: 0,
minHeight: 0,
maxWidth: constraints.maxWidth,
maxHeight: constraints.maxHeight);
print("getConstraintsForChild: ${relaxConstraint}}");
return relaxConstraint;
}
// 子widgte的位置
Offset getPositionForChild(Size size, Size childSize) {
print("getPositionForChild");
return Offset((size.width - childSize.width) * (xFactor + 1) * 0.5,
(size.height - childSize.height) * (1 + yFactor) * 0.5);
}
// 是否需要重绘
bool shouldRelayout(covariant SingleChildLayoutDelegate oldDelegate) {
return false;
}
}
其中有一个shouldRelayout
表示是否需要重新布局。由于Center就是居中,没有调整的参数,所以不需要在delegate改变时重新布局,这里就返回false。如果是类似于Align的布局,需要在alignment改变时重新布局,这里就需要判断alignment是否改变了。最后简单的封装一下,就可以和Center一样使用了。
scala
class CustomCenter extends StatelessWidget {
final Widget? child;
const CustomAlign(
{super.key, this.child});
@override
Widget build(BuildContext context) {
return CustomSingleChildLayout(
delegate: CustomCenterDelegate(),
child: child,
);
}
}
更进一步,源码分析
进一步分析源码,可以发现CustomSingleChildLayout
主要依赖于RenderCustomSingleChildLayoutBox
csharp
@override
RenderCustomSingleChildLayoutBox createRenderObject(BuildContext context) {
return RenderCustomSingleChildLayoutBox(delegate: delegate);
}
@override
void updateRenderObject(BuildContext context, RenderCustomSingleChildLayoutBox renderObject) {
renderObject.delegate = delegate;
}
RenderCustomSingleChildLayoutBox
中的核心则是performLayout
,performLayout
的代码简单明了
ini
@override
void performLayout() {
// 当前Widget从父Widget获取到约束,确定自身大小
size = _getSize(constraints);
if (child != null) {
// 当前Widget向子级Widget传递约束
final BoxConstraints childConstraints = delegate.getConstraintsForChild(constraints);
assert(childConstraints.debugAssertIsValid(isAppliedConstraint: true));
// 子级通过约束确定自身大小
child!.layout(childConstraints, parentUsesSize: !childConstraints.isTight);
final BoxParentData childParentData = child!.parentData! as BoxParentData;
// 当前Widget综合子级Widget大小和自身大小确定子级Widget位置
childParentData.offset = delegate.getPositionForChild(size, childConstraints.isTight ? childConstraints.smallest : child!.size);
}
}
多child容器
案例分析
多child的布局会复杂很多,比如Row组件,他的布局过程如下
- 将所有flex为0的 子Widgets(比如非Expanded)布局,使用的约束为主轴(mainAxis)不限制,交叉轴(crossAxis)使用传入的交叉轴约束
- 将剩余的主轴空间按照flex不为0的Widgets比例分割,比如三个flex为1的Widget,主轴方向上各得到1/3
- flex不为0的Widgets使用分到的主轴长度和传入的交叉轴约束进行布局
- Row的高度取子Widget最高
- Row的宽度和mainAxisSize有关,如果是max,则取父Widget的最大宽,min则取子Widgets宽度之和
- 根据mainAxisAlignment和crossAxisAlignment进行子Widgets位置计算
按照基本布局法则做映射的话
- 当前Widget从父Widget获取到约束 => 使用了父Widget的交叉轴约束
- 当前Widget向子级Widget传递约束,子级通过约束确定自身大小 => 1,2,3步总的来说就是给不同子Widget分配不同约束,从而计算子Widget尺寸
- 当前Widget综合子级Widget大小和自身大小确定子级Widget位置 => 4,5,6通过子Widget反算Row宽高,从而进一步决定子Widget位置
- 当前Widget将尺寸信息传递给父Widget,完成闭环 => Row的最终大小会被传递给父Widget做上层的布局
Row源码分析
接下来我们对照Row的源码来进一步感受布局的过程,Row继承自Flex,Flex中真正进行布局的是RenderFlex类的performLayout方法
ini
@override
void performLayout() {
...
// 计算子Widgets的尺寸,包含1,2,3三个步骤
final _LayoutSizes sizes = _computeSizes(
layoutChild: ChildLayoutHelper.layoutChild,
constraints: constraints,
);
...
// 根据计算的尺寸设置子Widget位置
// Position elements
double childMainPosition = flipMainAxis ? actualSize - leadingSpace : leadingSpace;
RenderBox? child = firstChild;
while (child != null) {
final FlexParentData childParentData = child.parentData! as FlexParentData;
final double childCrossPosition;
switch (_crossAxisAlignment) {
case CrossAxisAlignment.start:
case CrossAxisAlignment.end:
childCrossPosition = _startIsTopLeft(flipAxis(direction), textDirection, verticalDirection)
== (_crossAxisAlignment == CrossAxisAlignment.start)
? 0.0
: crossSize - _getCrossSize(child.size);
case CrossAxisAlignment.center:
childCrossPosition = crossSize / 2.0 - _getCrossSize(child.size) / 2.0;
case CrossAxisAlignment.stretch:
childCrossPosition = 0.0;
case CrossAxisAlignment.baseline:
if (_direction == Axis.horizontal) {
assert(textBaseline != null);
final double? distance = child.getDistanceToBaseline(textBaseline!, onlyReal: true);
if (distance != null) {
childCrossPosition = maxBaselineDistance - distance;
} else {
childCrossPosition = 0.0;
}
} else {
childCrossPosition = 0.0;
}
}
if (flipMainAxis) {
childMainPosition -= _getMainSize(child.size);
}
switch (_direction) {
case Axis.horizontal:
childParentData.offset = Offset(childMainPosition, childCrossPosition);
case Axis.vertical:
childParentData.offset = Offset(childCrossPosition, childMainPosition);
}
if (flipMainAxis) {
childMainPosition -= betweenSpace;
} else {
childMainPosition += _getMainSize(child.size) + betweenSpace;
}
child = childParentData.nextSibling;
}
}
再来分析下_computeSizes
的实现 第一步就是计算flex为0的子Widgets尺寸
ini
double crossSize = 0.0;
double allocatedSize = 0.0; // Sum of the sizes of the non-flexible children.
RenderBox? child = firstChild;
RenderBox? lastFlexChild;
while (child != null) {
final FlexParentData childParentData = child.parentData! as FlexParentData;
final int flex = _getFlex(child);
if (flex > 0) {
totalFlex += flex;
lastFlexChild = child;
} else {
final BoxConstraints innerConstraints;
if (crossAxisAlignment == CrossAxisAlignment.stretch) {
switch (_direction) {
case Axis.horizontal:
innerConstraints = BoxConstraints.tightFor(height: constraints.maxHeight);
case Axis.vertical:
innerConstraints = BoxConstraints.tightFor(width: constraints.maxWidth);
}
} else {
switch (_direction) {
case Axis.horizontal:
innerConstraints = BoxConstraints(maxHeight: constraints.maxHeight);
case Axis.vertical:
innerConstraints = BoxConstraints(maxWidth: constraints.maxWidth);
}
}
final Size childSize = layoutChild(child, innerConstraints);
allocatedSize += _getMainSize(childSize);
crossSize = math.max(crossSize, _getCrossSize(childSize));
}
assert(child.parentData == childParentData);
child = childParentData.nextSibling;
}
可以看到如果是flex大于0,则统计flex到totalFlex中。对于flex为0的Widget则只针对cross方向构造约束进行布局。如果cross对齐是stretch模式,则使用tight约束保证cross方向撑满
ini
if (crossAxisAlignment == CrossAxisAlignment.stretch) {
switch (_direction) {
case Axis.horizontal:
innerConstraints = BoxConstraints.tightFor(height: constraints.maxHeight);
case Axis.vertical:
innerConstraints = BoxConstraints.tightFor(width: constraints.maxWidth);
}
} else {
switch (_direction) {
case Axis.horizontal:
innerConstraints = BoxConstraints(maxHeight: constraints.maxHeight);
case Axis.vertical:
innerConstraints = BoxConstraints(maxWidth: constraints.maxWidth);
}
}
第二步开始计算flex大于0的子Widgets尺寸
ini
// Distribute free space to flexible children.
final double freeSpace = math.max(0.0, (canFlex ? maxMainSize : 0.0) - allocatedSize);
double allocatedFlexSpace = 0.0;
// totalFlex大于0表示有flex不为0的子Widget
if (totalFlex > 0) {
final double spacePerFlex = canFlex ? (freeSpace / totalFlex) : double.nan;
child = firstChild;
while (child != null) {
final int flex = _getFlex(child);
if (flex > 0) {
// 计算出这个子Widget在主轴可被分配的最大尺寸
final double maxChildExtent = canFlex ? (child == lastFlexChild ? (freeSpace - allocatedFlexSpace) : spacePerFlex * flex) : double.infinity;
late final double minChildExtent;
// 针对FlexFit分配不同约束,这就是Expanded和Flexible的区别,Expanded采用FlexFit.tight模式,Flexible则是FlexFit.loose
switch (_getFit(child)) {
case FlexFit.tight:
assert(maxChildExtent < double.infinity);
minChildExtent = maxChildExtent;
case FlexFit.loose:
minChildExtent = 0.0;
}
// 这块和flex为0基本一致,为子Widget构建约束,计算尺寸
final BoxConstraints innerConstraints;
if (crossAxisAlignment == CrossAxisAlignment.stretch) {
switch (_direction) {
case Axis.horizontal:
innerConstraints = BoxConstraints(
minWidth: minChildExtent,
maxWidth: maxChildExtent,
minHeight: constraints.maxHeight,
maxHeight: constraints.maxHeight,
);
case Axis.vertical:
innerConstraints = BoxConstraints(
minWidth: constraints.maxWidth,
maxWidth: constraints.maxWidth,
minHeight: minChildExtent,
maxHeight: maxChildExtent,
);
}
} else {
switch (_direction) {
case Axis.horizontal:
innerConstraints = BoxConstraints(
minWidth: minChildExtent,
maxWidth: maxChildExtent,
maxHeight: constraints.maxHeight,
);
case Axis.vertical:
innerConstraints = BoxConstraints(
maxWidth: constraints.maxWidth,
minHeight: minChildExtent,
maxHeight: maxChildExtent,
);
}
}
final Size childSize = layoutChild(child, innerConstraints);
final double childMainSize = _getMainSize(childSize);
assert(childMainSize <= maxChildExtent);
allocatedSize += childMainSize;
allocatedFlexSpace += maxChildExtent;
crossSize = math.max(crossSize, _getCrossSize(childSize));
}
final FlexParentData childParentData = child.parentData! as FlexParentData;
child = childParentData.nextSibling;
}
}
最后一步,通过计算出来的子Widget尺寸,计算Row的尺寸,这里主要就是判断mainAxisSize
,看需要最大值还是真实的子Widget宽度和。
arduino
final double idealSize = canFlex && mainAxisSize == MainAxisSize.max ? maxMainSize : allocatedSize;
CustomMultiChildLayout
最后再介绍一个用于自定义多child布局的Widget,和单child类似,需要实现一个delegate
less
class CustomRowDelegate extends MultiChildLayoutDelegate {
@override
void performLayout(Size size) {
}
@override
bool shouldRelayout(covariant MultiChildLayoutDelegate oldDelegate) {
}
}
方法很简单,就2个,这里需要注意的是,和上面介绍的Row布局不同,这里能够布局的尺寸已经固定了,子Widget无法影响CustomMultiChildLayout
的尺寸,CustomMultiChildLayout
的尺寸就是performLayout
传递的Size。
比如我们想要实现一个横向自动均分子Widget的容器,可以这么写
arduino
@override
void performLayout(Size size) {
if (keys != null) {
// 对横向的空间进行均分
final childWidth = size.width / keys!.length;
var offsetX = 0.0;
for (final String key in keys!) {
// 横向构造严格约束,纵向构造宽松约束,从而让子Widget横向使用均分的尺寸,纵向使用自己的尺寸
final constraits = BoxConstraints(minWidth: childWidth, maxWidth: childWidth, minHeight: 0, maxHeight: size.height);
final childSize = layoutChild(key, constraits);
// 对于纵向让子Widget居中
positionChild(key, Offset(offsetX, (size.height - childSize.height) * 0.5));
offsetX += childSize.width;
}
}
}
CustomMultiChildLayout规定每个子Widget必须都是LayoutId
php
(id: "1", child: Container(height: 60, color: Colors.yellow,),),
在布局子Widget时以它的id作为凭证
ini
final childSize = layoutChild(key, constraits);
最后使用这个自定义的Widget
less
class CustomRow extends StatelessWidget {
final List<Widget>? children;
final List<String>? keys;
const CustomRow(
{super.key, this.children, this.keys});
@override
Widget build(BuildContext context) {
return CustomMultiChildLayout(
delegate: CustomRowDelegate(keys: keys),
children: children ?? [],
);
}
}
...
CustomRow(
keys: const ["1", "2", "3"],
children: [
LayoutId(id: "1", child: Container(height: 60, color: Colors.yellow,),),
LayoutId(id: "2", child: Container(height: 80, color: Colors.red,),),
LayoutId(id: "3", child: Container(height: 40, color: Colors.green,),),
],
),
总结
通过对布局原理的了解,在布局的时候可以更加清晰的预测UI的效果,每当遇到一个新布局Widget,就可以通过四个步骤去梳理他的布局过程,通过文档和开源的代码,就可以很深入的掌握它的特性了。