Widget、Element、RenderObject 三者之间的关系在<<六、深入了解绘制原理>>已经讲解过,其中我们最为熟知的 Widget ,究竟是通过什么样的方式来实现代码搭积木实现建造房子呢?
单子元素布局–SingleChildRenderObjectWidget
Container
Container是继承StatelessWidget,那么build是构建布局关键函数,在Container中build中,掺杂了很多其他的部件,Align、Padding、ColoredBox、DecorateBox、Transform…等等,每个关于布局或者样式的属性,最后都被转化成其他的box来呈现。看下官方源码:
@override
Widget build(BuildContext context) {
Widget current = child;
if (child == null && (constraints == null || !constraints.isTight)) {
current = LimitedBox(
maxWidth: 0.0,
maxHeight: 0.0,
child: ConstrainedBox(constraints: const BoxConstraints.expand()),
);
}
/// 封装 Align
if (alignment != null)
current = Align(alignment: alignment, child: current);
final EdgeInsetsGeometry effectivePadding = _paddingIncludingDecoration;
if (effectivePadding != null)
/// 封装 Padding
current = Padding(padding: effectivePadding, child: current);
if (color != null)
/// 封装 ColoredBox
current = ColoredBox(color: color, child: current);
/// 封装DecoratedBox
if (decoration != null)
current = DecoratedBox(decoration: decoration, child: current);
/// 封装 DecoratedBox
if (foregroundDecoration != null) {
current = DecoratedBox(
decoration: foregroundDecoration,
position: DecorationPosition.foreground,
child: current,
);
}
/// 封装 ConstrainedBox
if (constraints != null)
current = ConstrainedBox(constraints: constraints, child: current);
/// 封装 Padding
if (margin != null)
current = Padding(padding: margin, child: current);
/// 封装 Transform
if (transform != null)
current = Transform(transform: transform, child: current);
/// 封装 ClipPath
if (clipBehavior != Clip.none) {
current = ClipPath(
clipper: _DecorationClipper(
textDirection: Directionality.of(context),
decoration: decoration
),
clipBehavior: clipBehavior,
child: current,
);
}
return current;
}
Padding/Transform/ConstraineBox...都是继承SingleChildRenderObjectWidget,通过SingleChildRenderObjectWidget实现的布局。
Padding通过创建渲染实例RenderPadding

最低0.47元/天 解锁文章
510

被折叠的 条评论
为什么被折叠?



