Flutter渲染原理

一  Widget Element RenderObject 之间的关系

1   Widget

在Flutter 中,万物皆是Widget,无论是可见的还是功能型的。一切都是Widget.

官方文档中说的Widget 使用配置和状态来描述View 界面应该长什么样子。

它不仅可以表示UI元素,也可以表示一些功能性的组件如:用于手势检测的 GestureDetector、用于APP主题数据传递的Theme、布局元素等等

两个重要的方法

一个是通过 createElement 来创建 Element 对象的,

一个是根据 key 来决定更新行为的 canUpdate 方法。

在这个方法中会对比runtimeType (也就是widget 的类型)和 key 是否相同

@immutable
abstract class Widget extends DiagnosticableTree {
  /// Initializes [key] for subclasses.
  const Widget({this.key});
  
  
  final Key? key;

 
  @protected
  @factory
  Element createElement();

  /// A short, textual description of this widget.
  @override
  String toStringShort() {
    final String type = objectRuntimeType(this, 'Widget');
    return key == null ? type : '$type-$key';
  }

  @override
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
    properties.defaultDiagnosticsTreeStyle = DiagnosticsTreeStyle.dense;
  }

  @override
  @nonVirtual
  bool operator ==(Object other) => super == other;

  @override
  @nonVirtual
  int get hashCode => super.hashCode;

  
  static bool canUpdate(Widget oldWidget, Widget newWidget) {
    return oldWidget.runtimeType == newWidget.runtimeType &&
        oldWidget.key == newWidget.key;
  }

  // Return a numeric encoding of the specific `Widget` concrete subtype.
  // This is used in `Element.updateChild` to determine if a hot reload modified the
  // superclass of a mounted element's configuration. The encoding of each `Widget`
  // must match the corresponding `Element` encoding in `Element._debugConcreteSubtype`.
  static int _debugConcreteSubtype(Widget widget) {
    return widget is StatefulWidget
        ? 1
        : widget is StatelessWidget
            ? 2
            : 0;
  }
}

2   Element

Element 就是一个Widget 的实例,在树中详细的位置。

An instantiation of a Widget at a particular location in the tree

3 RenderObject

渲染树上的一个对象。负责具体布局和绘制这些事情。

4 结合图说一下其三者的关系

从创建到渲染的流程 :

根据Widget 生成Element,然后创建响应的RenderObject并且关联到Element.renderObject 属性。最后再通过RenderObject 来完成布局和绘制。

依赖关系:

Element 树根据Widget 树生成,而渲染树又依赖于widget 树。

5 一些小问题?

5.1  widget 和 element 是一一对应的吗 ? 为什么 ?

答:是一一对应的。

因为 abstract class Widget ,本身是一个抽象类,这个抽象类中有一个抽象方法叫做createElement(),子类必须实现这个抽象方法,所以是一一对应的。

5.2 widget 和 renderObject 是一一对应的吗 ? 为什么 ?

答:不是的

因为只有这个widget 继承自RenderObjectWidget 的时候,才会有对应的renderObject
像类似 Padding , Row,SizedBox,Center 这种组件继承自RenderObjectWidget的组件会有一一对应的关系


//class Padding extends SingleChildRenderObjectWidget

// Padding();

// class Flex extends MultiChildRenderObjectWidget

// Row()

5.3 BuildContext 是什么 ?

答:是Element,不管是StatefulWidget 还是StatelessWidget 都会重写父类的build 方法,

build 方法传入的一个参数叫做BuildContext, 我们拿StatelessWidget来说,其本身创建一个StatelessElement,而在这个Element内部重写StatelessElement父类的build方法,而在这个build方法内部会调用_widget.build 方法,并且把this传递进去。那么这个this 就是element 。

/// An [Element] that uses a [StatelessWidget] as its configuration.
class StatelessElement extends ComponentElement {
  /// Creates an element that uses the given widget as its configuration.
  StatelessElement(StatelessWidget super.widget);

  @override
  Widget build() => (widget as StatelessWidget).build(this);

  @override
  void update(StatelessWidget newWidget) {
    super.update(newWidget);
    assert(widget == newWidget);
    _dirty = true;
    rebuild();
  }
}

5.4 Widget 频繁更改创建是否会影响性能?复用和更新机制是什么样的?

不会影响性能,因为只是一些配置信息,没有有布局渲染到页面上去。中间层Element 会通过widget 的runtimeType 和 Key 来对比是否进行更新操作。

5.5 Build 方法会在什么时候调用 ?

Element 创建完毕之后会调用mount 方法,对于非渲染的ComponentElement 来说,mount主要执行的是Widget 中的build 方法。在StatelessElement 中直接使用的是 widget.build(this),

而在StatefullWidget 方法中,通过的是state.build(this)。在StatefulElement 这个类中,

初始化列表的给state 进行了赋值操作。通过widget调用createState方法之后,把state赋值给自己的_state 属性。

StatefulElement(StatefulWidget widget)

: _state = widget.createState(),

5.6 createState 方法什么时候调用?

答:创建Element 的时候。

Flutter 会在遍历 Widget 树时调用 Widget 里面的 createElement 方法去生成对应节点的 Element 对象,同时执行 StatefulWidget 里面的 createState 方法创建 state,并且赋值给 Element 里的 _state 属性,当前 widget 也同时赋值给了 state 里的_widget,state 里面有个 widget 的get 方法可以获取到 _widget 对象。
 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Flutter渲染机制可以从源码角度来理解。Flutter渲染与两个线程直接相关,分别是UI线程和GPU线程。UI线程负责执行Dart root isolate代码,并将其转换为Layer tree。 Layer 是 Flutter Framework 中的一个重要概念,它代表了一块矩形区域,可以包含图形、文本、图片等内容。这些 Layer 最终会被提交到 Engine 中进行绘制。 Layer 的工作原理是将所有的绘制操作转化为一系列的绘制指令,然后将这些指令传递给 GPU 线程进行绘制。 Flutter Framework 中的绘制过程经过多个步骤,包括布局、绘制、合成等,最终将所有的 Layer 组合在一起形成最终的界面。通过理解 Flutter渲染原理,开发者可以更清晰地了解应用程序的渲染过程,并进行性能优化。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [Flutter渲染机制—UI线程](https://download.csdn.net/download/weixin_38550834/15446392)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* *3* [Flutter 画面渲染的全面解析](https://blog.csdn.net/chengjiamei/article/details/107974790)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值