Flutter 详解(八、深入了解布局)

WidgetElementRenderObject 三者之间的关系在<<六、深入了解绘制原理>>已经讲解过,其中我们最为熟知的 Widget ,究竟是通过什么样的方式来实现代码搭积木实现建造房子呢?

单子元素布局--SingleChildRenderObjectWidget

Container

Container是继承StatelessWidget,那么build是构建布局关键函数,在Container中build中,掺杂了很多其他的部件,AlignPaddingColoredBoxDecorateBoxTransform...等等,每个关于布局或者样式的属性,最后都被转化成其他的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,在更新实例的时候,更新该实例的属性。Align通过创建RenderPositionedBox来实现渲染实例,其他的如下表所示:

部件 渲染对象
Padding RenderPadding
Align RenderPositionedBox
ColoredBox _RenderColoredBox
DecoratedBox RenderDecoratedBox
ConstrainedBox RenderConstrainedBox
Transform RenderTransform
ClipPath RenderClipPath

...

他们有一个共同点都是继承SingleChildRenderObjectWidget,而createRenderObject返回了不同的渲染对象RenderBox,RenderBox最终实现位置偏移和大小,都是通过RenderBox来实现的,所以找每个组件的RenderBox的实现就可以看到他们是怎么布局的。

Padding是一个继承RenderPaddingRenderPadding继承了RenderShiftedBox,RenderShiftedBox继承了RenderBox,那么我们就拿Padding举例子讲解下。

RenderShiftedBox实现了获取组件的宽度和高度,子组件为空,则返回0.0,这里实现了computeMinIntrinsicWidthcomputeMaxIntrinsicWidthcomputeMinIntrinsicHeightcomputeMaxIntrinsicHeight和最终绘画函数paint(PaintingContext context, Offset offset),把UI绘画出来。

abstract class RenderShiftedBox extends RenderBox with RenderObjectWithChildMixin<RenderBox> {
  /// Initializes the [child] property for subclasses.
  RenderShiftedBox(RenderBox child) {
    this.child = child;
  }

  @override
  double computeMinIntrinsicWidth(double height) {
    if (child != null)
      return child.getMinIntrinsicWidth(height);
    return 0.0;
  }

  @override
  double computeMaxIntrinsicWidth(double height) {
    if (child != null)
      return child.getMaxIntrinsicWidth(height);
    return 0.0;
  }

  @override
  double computeMinIntrinsicHeight(double width) {
    if (child != null)
      return child.getMinIntrinsicHeight(width);
    return 0.0;
  }

  @override
  double computeMaxIntrinsicHeight(double width) {
    if (child != null)
      return child.getMaxIntrinsicHeight(width);
    return 0.0;
  }

  @override
  double computeDistanceToActualBaseline(TextBaseline baseline) {
    double result;
    if (child != null) {
      assert(!debugNeedsLayout);
      result = child.getDistanceToActualBaseline(baseline);
      final BoxParentData childParentData = child.parentData as BoxParentData;
      if (result != null)
        result += childParentData.offset.dy;
    } else {
      result = super.computeDistanceToActualBaseline(baseline);
    }
    return result;
  }

  @override
  void paint(PaintingContext context, Offset offset) {
    if (child != null) {
      final BoxParentData childParentData = child.parentData as BoxParentData;
      context.paintChild(child, childParentData.offset + offset);
    }
  }

  @override
  bool hitTestChildren(BoxHitTestResult result, { Offset position }) {
    if (child != null) {
      final BoxParentData childParentData = child.parentData as BoxParentData;
      return result.addWithPaintOffset(
        offset: childParentData.offset,
        position: position,
        hitTest: (BoxHitTestResult result, Offset transformed) {
          assert(transformed == position - childParentData.offset);
          return child.hitTest(result, position: transformed);
        },
      );
    }
    return false;
  }

}

我们通过Padding来看下源码如何实现布局的:

  @override
  double computeMinIntrinsicWidth(double height) {
    _resolve();
    final double totalHorizontalPadding = _resolvedPadding.left + _resolvedPadding.right;
    final double totalVerticalPadding = _resolvedPadding.top + _resolvedPadding.bottom;
    if (child != null) // next line relies on double.infinity absorption
      return child.getMinIntrinsicWidth(math.max(0.0, height - totalVerticalPadding)) + totalHorizontalPadding;
    return totalHorizontalPadding;
  }

这里通过getMinIntrinsicWidth()来获取最小宽度。


@override
double computeMaxIntrinsicWidth(double height) {
_resolve();
final double totalHorizontalPadding = _resolvedPadding.left + _resolvedPadding.right;
final double totalVerticalPadding = _resolvedPadding.top + _resolvedPadding.bottom;
if (child != null) // next line relies on double.infinity absorption
  return child.getMaxIntrinsicWidth(math.max(0.0, height - totalVerticalPadding)) + totalHorizontalPadding;
return totalHorizontalPadding;
}

通过getMaxIntrinsicWidth获获得最大宽度,通过computeMaxIntrinsicHeight获取最大高度,通过computeMinIntrinsicHeight最小高度,当高度和宽度都计算了之后,然后进行布局。

那么作为开发者可以自己通过RenderBox来实现一个新的布局组件吗?当然是可以的,只要你觉得有必要的话。否则官方提供的布局组件足够满足我们的使用了。

其实官方已提供一个抽象接口SingleChildLayoutDelegate,让开发者自己实现一个布局。

abstract class SingleChildLayoutDelegate {
 
/// 监听
 final Listenable _relayout;
  /// 获取大小
 Size getSize(BoxConstraints constraints) => constraints.biggest;
/// 获取子部件的约束
 BoxConstraints getConstraintsForChild(BoxConstraints constraints) => constraints;
/// 获取子部件的位置
 Offset getPositionForChild(Size size, Size childSize) => Offset.zero;

/// 是否需要更新
 bool shouldRelayout(covariant SingleChildLayoutDelegate oldDelegate);
}

多子元素 MultiChildRenderObjectWidget

多子元素和单子元素基本一致,RowColumn继承了FlexFlex继承了MultiChildRenderObjectWidget,MultiChildRenderObjectWidget中的RenderFlex通过继承RenderBox来实现的布局样式。

部件 渲染对象
Column、Row、Flex RenderFlex
Stack RenderStack
Flow RenderFlow
Wrap RenderWrap

同样的 多子元素也提供了供开发者自己实现布局的抽象接口CustomMultiChildLayoutMultiChildLayoutDelegate.

滑动 多子布局

滑动布局也是多子布局的一种,如各种ListViewGridViewCustomview他们在实现过程很复杂,从下面的一个流程我们可以大致了解他们的关系。

image

由上图我们可以知道,最终会产生两个渲染对象RenderObject

并且从 RenderViewport的说明我们了解到,RenderViewport内部是不能直接放置 RenderBox,需要通过 RenderSliver让大家族来完成布局。而从源码可以了解到:RenderViewport 对应的 Widget Viewport 就是一个 MultiChildRenderObjectWidget

再稍微说下上图的流程:

ListView、Pageview、GridView 等都是通过 ScrollableViewPortSliver大家族实现的效果。这里简单总结下就是:一个“可滑动”的控件,嵌套了一个“视觉窗口”,然后内部通过“碎片”展示 children
不同的是 PageView 没有继承 SrollView,而是直接通过 NotificationListenerScrollNotification 嵌套实现。

官方同样提供的自定义滑动 CustomScrollView,它继承了 ScrollView,可通过 slivers 参数实现子控件布局, slivers 是通过 ScrollablebuildViewport 添加到 ViewPort 中,如下代码所示:

CustomScrollView(
    slivers: <Widget>[
      SliverList(
        delegate: SliverChildBuilderDelegate((context, index) {
          return Text('$index');
        }, childCount: 10),
      ),
      SliverGrid(
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 3,
          crossAxisSpacing: 10,
          mainAxisSpacing: 10,
        ),
        delegate: SliverChildBuilderDelegate((context, index) {
          return Text('$index');
        }, childCount: 12),
      )
    ],
  )

文章汇总

Dart 异步与多线程

Flutter 详解(一、深入了解状态管理--ScopeModel

Flutter 详解(二、深入了解状态管理--Redux)

Flutter 详解(三、深入了解状态管理--Provider)

Flutter 详解(四、深入了解状态管理--BLoC)

Flutter 详解 (五、深入了解--Key)

Flutter 详解 (六、深入了解--Stream

Flutter 详解(七、深入了解绘制原理

Flutter 详解(八、深入了解布局)

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,716评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,558评论 1 294
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,431评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,127评论 0 209
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,511评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,692评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,915评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,664评论 0 202
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,412评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,616评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,105评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,424评论 2 254
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,098评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,096评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,869评论 0 197
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,748评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,641评论 2 271