Flutter开发进阶之瞧瞧RenderObject

2024-03-24 03:44

本文主要是介绍Flutter开发进阶之瞧瞧RenderObject,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

Flutter开发进阶之瞧瞧RenderObject

通过上回我们了解到Flutter执行buildTree的逻辑线,当Tree构建完成后会交给Flutter底层的渲染事件循环去执行将内容渲染到屏幕的操作。
但是渲染的操作到底是如何串起来的呢?这篇文章将会从Element联系到RenderObject去瞧瞧逻辑线形成闭环。
Flutter开发进阶
在Element的源码中有一个方法,如下。

/*
### RebuildingDirty elements are rebuilt during the next frame. Precisely how this isdone depends on the kind of element. A [StatelessElement] rebuilds byusing its widget's [StatelessWidget.build] method. A [StatefulElement]rebuilds by using its widget's state's [State.build] method. A[RenderObjectElement] rebuilds by updating its [RenderObject].In many cases, the end result of rebuilding is a single child widgetor (for [MultiChildRenderObjectElement]s) a list of children widgets.These child widgets are used to update the [widget] property of theelement's child (or children) elements. The new [Widget] is considered tocorrespond to an existing [Element] if it has the same [Type] and [Key].(In the case of [MultiChildRenderObjectElement]s, some effort is put intotracking widgets even when they change order; see[RenderObjectElement.updateChildren].)
*/
('vm:prefer-inline')
void rebuild({bool force = false})

我们通过注释可知,Element在构建好Tree后,Dirty elements在下一帧重建,无论是多子Element还是单子Element都是通过RenderObjectElement更新它的RenderObject完成。
让我们来看看RenderObjectElementmount方法,以下。

void mount(Element? parent, Object? newSlot) {super.mount(parent, newSlot);assert(() {_debugDoingBuild = true;return true;}());_renderObject = (widget as RenderObjectWidget).createRenderObject(this);assert(!_renderObject!.debugDisposed!);assert(() {_debugDoingBuild = false;return true;}());assert(() {_debugUpdateRenderObjectOwner();return true;}());assert(_slot == newSlot);attachRenderObject(newSlot);super.performRebuild(); // clears the "dirty" flag}
void attachRenderObject(Object? newSlot) {assert(_ancestorRenderObjectElement == null);_slot = newSlot;_ancestorRenderObjectElement = _findAncestorRenderObjectElement();_ancestorRenderObjectElement?.insertRenderObjectChild(renderObject, newSlot);final ParentDataElement<ParentData>? parentDataElement = _findAncestorParentDataElement();if (parentDataElement != null) {_updateParentData(parentDataElement.widget as ParentDataWidget<ParentData>);}}

RenderObjectElement装载RenderObject的过程中,会创建一个RenderObject与其对应,然后将RenderObject插入对应的卡槽(Slot),并且还需保证子RenderObject遵循上级Widget的相关配置。
根据事件线的逻辑,接下来将看到RenderObject的逻辑,源码代码太长就不一一贴了。

abstract class RenderObjectwith DiagnosticableTreeMixinimplements HitTestTarget

RenderObject不仅负责Layout、Paint还需要负责hit,这里我们只考虑Layout和Paint
让我们看看markNeedsLayout,以下。

void markNeedsLayout() {assert(_debugCanPerformMutations);if (_needsLayout) {assert(_debugSubtreeRelayoutRootAlreadyMarkedNeedsLayout());return;}if (_relayoutBoundary == null) {_needsLayout = true;if (parent != null) {// _relayoutBoundary is cleaned by an ancestor in RenderObject.layout.// Conservatively mark everything dirty until it reaches the closest// known relayout boundary.markParentNeedsLayout();}return;}if (_relayoutBoundary != this) {markParentNeedsLayout();} else {_needsLayout = true;if (owner != null) {assert(() {if (debugPrintMarkNeedsLayoutStacks) {debugPrintStack(label: 'markNeedsLayout() called for $this');}return true;}());owner!._nodesNeedingLayout.add(this);owner!.requestVisualUpdate();}}}

可以看到渲染的逻辑线是推迟到parent的,当合成的Layout需要执行渲染时,会交给owner并添加进需要Layout的集合里,然后通过owner!.requestVisualUpdate();去通知渲染管线进行渲染。
让我们看看源码中怎么说,以下。

/// The owner for this render object (null if unattached).////// The entire render tree that this render object belongs to/// will have the same owner.PipelineOwner? get owner => _owner;PipelineOwner? _owner;

可知在同一个Tree以下都对应同一个PipelineOwner,这个owner负责管理具体的渲染工作,相当于前文说到的ElementBuildOwner的关系。
接下来来我们看看markNeedsPaint方法,以下。

void markNeedsPaint() {assert(!_debugDisposed);assert(owner == null || !owner!.debugDoingPaint);if (_needsPaint) {return;}_needsPaint = true;// If this was not previously a repaint boundary it will not have// a layer we can paint from.if (isRepaintBoundary && _wasRepaintBoundary) {assert(() {if (debugPrintMarkNeedsPaintStacks) {debugPrintStack(label: 'markNeedsPaint() called for $this');}return true;}());// If we always have our own layer, then we can just repaint// ourselves without involving any other nodes.assert(_layerHandle.layer is OffsetLayer);if (owner != null) {owner!._nodesNeedingPaint.add(this);owner!.requestVisualUpdate();}} else if (parent is RenderObject) {parent!.markNeedsPaint();} else {assert(() {if (debugPrintMarkNeedsPaintStacks) {debugPrintStack(label: 'markNeedsPaint() called for $this (root of render tree)');}return true;}());// If we are the root of the render tree and not a repaint boundary// then we have to paint ourselves, since nobody else can paint us.// We don't add ourselves to _nodesNeedingPaint in this case,// because the root is always told to paint regardless.//// Trees rooted at a RenderView do not go through this// code path because RenderViews are repaint boundaries.if (owner != null) {owner!.requestVisualUpdate();}}}

markNeedsPaintRepaintBoundary会将渲染子Tree限制在自己的范围内,与markNeedsLayout类似,而且也会通过owner去执行渲染管线的管理。
让我们看看PipelineOwner是如何执行的?

/// Calls [onNeedVisualUpdate] if [onNeedVisualUpdate] is not null.////// Used to notify the pipeline owner that an associated render object wishes/// to update its visual appearance.void requestVisualUpdate() {if (onNeedVisualUpdate != null) {onNeedVisualUpdate!();} else {_manifold?.requestVisualUpdate();}}

在Flutter中,PipelineOwner负责渲染管线的各个方面,是具体与WidgetsBindingRendererBinding帧事件循环的交互。
让我们看看onNeedVisualUpdate的注释,以下。

/// Called when a render object associated with this pipeline owner wishes to/// update its visual appearance.////// Typical implementations of this function will schedule a task to flush the/// various stages of the pipeline. This function might be called multiple/// times in quick succession. Implementations should take care to discard/// duplicate calls quickly.////// When the [PipelineOwner] is attached to a [PipelineManifold] and/// [onNeedVisualUpdate] is provided, the [onNeedVisualUpdate] callback is/// invoked instead of calling [PipelineManifold.requestVisualUpdate].final VoidCallback? onNeedVisualUpdate;

可知作为一个调度任务可能被多次重复调用,当PipelineOwner连接到PipelineManifold并提供onNeedVisualUpdate时,会直接执行onNeedVisualUpdate
继续查看PipelineManifold,以下。

abstract class PipelineManifold implements Listenable {/// Whether [PipelineOwner]s connected to this [PipelineManifold] should/// collect semantics information and produce a semantics tree.////// The [PipelineManifold] notifies its listeners (managed with [addListener]/// and [removeListener]) when this property changes its value.////// See also://////  * [SemanticsBinding.semanticsEnabled], which [PipelineManifold]///    implementations typically use to back this property.bool get semanticsEnabled;/// Called by a [PipelineOwner] connected to this [PipelineManifold] when a/// [RenderObject] associated with that pipeline owner wishes to update its/// visual appearance.////// Typical implementations of this function will schedule a task to flush the/// various stages of the pipeline. This function might be called multiple/// times in quick succession. Implementations should take care to discard/// duplicate calls quickly.////// A [PipelineOwner] connected to this [PipelineManifold] will call/// [PipelineOwner.onNeedVisualUpdate] instead of this method if it has been/// configured with a non-null [PipelineOwner.onNeedVisualUpdate] callback.////// See also://////  * [SchedulerBinding.ensureVisualUpdate], which [PipelineManifold]///    implementations typically call to implement this method.void requestVisualUpdate();
}

在Flutter中,PipelineManifold通常不会暴露在外,它管理PipelineOwner Tree下所有PipelineOwner,它实现了PipelineOwner访问共享,PipelineManifold通过调用SchedulerBinding.ensureVisualUpdate实现通知渲染执行。
让我们继续进行下一步的探索,以下。

/// Schedules a new frame using [scheduleFrame] if this object is not/// currently producing a frame.////// Calling this method ensures that [handleDrawFrame] will eventually be/// called, unless it's already in progress.////// This has no effect if [schedulerPhase] is/// [SchedulerPhase.transientCallbacks] or [SchedulerPhase.midFrameMicrotasks]/// (because a frame is already being prepared in that case), or/// [SchedulerPhase.persistentCallbacks] (because a frame is actively being/// rendered in that case). It will schedule a frame if the [schedulerPhase]/// is [SchedulerPhase.idle] (in between frames) or/// [SchedulerPhase.postFrameCallbacks] (after a frame).void ensureVisualUpdate() {switch (schedulerPhase) {case SchedulerPhase.idle:case SchedulerPhase.postFrameCallbacks:scheduleFrame();return;case SchedulerPhase.transientCallbacks:case SchedulerPhase.midFrameMicrotasks:case SchedulerPhase.persistentCallbacks:return;}}

继续沿SchedulerBinding的执行路径,以下。

void scheduleFrame() {if (_hasScheduledFrame || !framesEnabled) {return;}assert(() {if (debugPrintScheduleFrameStacks) {debugPrintStack(label: 'scheduleFrame() called. Current phase is $schedulerPhase.');}return true;}());ensureFrameCallbacksRegistered();platformDispatcher.scheduleFrame();_hasScheduledFrame = true;}

最终void scheduleFrame()是具体下一帧绘制的方法,由此完成闭环。
综上所述,我们了解到,Flutter具体执行渲染时会构建RenderObject Tree(通过将RenderObject插入Slot),具体操作交给PipelineOwner管理,而同一Tree下的PipelineOwner对接唯一的PipelineManifold,最后通知SchedulerBinding去执行帧绘制的操作。

这篇关于Flutter开发进阶之瞧瞧RenderObject的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/840362

相关文章

Spring Security 从入门到进阶系列教程

Spring Security 入门系列 《保护 Web 应用的安全》 《Spring-Security-入门(一):登录与退出》 《Spring-Security-入门(二):基于数据库验证》 《Spring-Security-入门(三):密码加密》 《Spring-Security-入门(四):自定义-Filter》 《Spring-Security-入门(五):在 Sprin

这15个Vue指令,让你的项目开发爽到爆

1. V-Hotkey 仓库地址: github.com/Dafrok/v-ho… Demo: 戳这里 https://dafrok.github.io/v-hotkey 安装: npm install --save v-hotkey 这个指令可以给组件绑定一个或多个快捷键。你想要通过按下 Escape 键后隐藏某个组件,按住 Control 和回车键再显示它吗?小菜一碟: <template

Hadoop企业开发案例调优场景

需求 (1)需求:从1G数据中,统计每个单词出现次数。服务器3台,每台配置4G内存,4核CPU,4线程。 (2)需求分析: 1G / 128m = 8个MapTask;1个ReduceTask;1个mrAppMaster 平均每个节点运行10个 / 3台 ≈ 3个任务(4    3    3) HDFS参数调优 (1)修改:hadoop-env.sh export HDFS_NAMENOD

Java进阶13讲__第12讲_1/2

多线程、线程池 1.  线程概念 1.1  什么是线程 1.2  线程的好处 2.   创建线程的三种方式 注意事项 2.1  继承Thread类 2.1.1 认识  2.1.2  编码实现  package cn.hdc.oop10.Thread;import org.slf4j.Logger;import org.slf4j.LoggerFactory

嵌入式QT开发:构建高效智能的嵌入式系统

摘要: 本文深入探讨了嵌入式 QT 相关的各个方面。从 QT 框架的基础架构和核心概念出发,详细阐述了其在嵌入式环境中的优势与特点。文中分析了嵌入式 QT 的开发环境搭建过程,包括交叉编译工具链的配置等关键步骤。进一步探讨了嵌入式 QT 的界面设计与开发,涵盖了从基本控件的使用到复杂界面布局的构建。同时也深入研究了信号与槽机制在嵌入式系统中的应用,以及嵌入式 QT 与硬件设备的交互,包括输入输出设

OpenHarmony鸿蒙开发( Beta5.0)无感配网详解

1、简介 无感配网是指在设备联网过程中无需输入热点相关账号信息,即可快速实现设备配网,是一种兼顾高效性、可靠性和安全性的配网方式。 2、配网原理 2.1 通信原理 手机和智能设备之间的信息传递,利用特有的NAN协议实现。利用手机和智能设备之间的WiFi 感知订阅、发布能力,实现了数字管家应用和设备之间的发现。在完成设备间的认证和响应后,即可发送相关配网数据。同时还支持与常规Sof

活用c4d官方开发文档查询代码

当你问AI助手比如豆包,如何用python禁止掉xpresso标签时候,它会提示到 这时候要用到两个东西。https://developers.maxon.net/论坛搜索和开发文档 比如这里我就在官方找到正确的id描述 然后我就把参数标签换过来

[MySQL表的增删改查-进阶]

🌈个人主页:努力学编程’ ⛅个人推荐: c语言从初阶到进阶 JavaEE详解 数据结构 ⚡学好数据结构,刷题刻不容缓:点击一起刷题 🌙心灵鸡汤:总有人要赢,为什么不能是我呢 💻💻💻数据库约束 🔭🔭🔭约束类型 not null: 指示某列不能存储 NULL 值unique: 保证某列的每行必须有唯一的值default: 规定没有给列赋值时的默认值.primary key:

Linux_kernel驱动开发11

一、改回nfs方式挂载根文件系统         在产品将要上线之前,需要制作不同类型格式的根文件系统         在产品研发阶段,我们还是需要使用nfs的方式挂载根文件系统         优点:可以直接在上位机中修改文件系统内容,延长EMMC的寿命         【1】重启上位机nfs服务         sudo service nfs-kernel-server resta

【区块链 + 人才服务】区块链集成开发平台 | FISCO BCOS应用案例

随着区块链技术的快速发展,越来越多的企业开始将其应用于实际业务中。然而,区块链技术的专业性使得其集成开发成为一项挑战。针对此,广东中创智慧科技有限公司基于国产开源联盟链 FISCO BCOS 推出了区块链集成开发平台。该平台基于区块链技术,提供一套全面的区块链开发工具和开发环境,支持开发者快速开发和部署区块链应用。此外,该平台还可以提供一套全面的区块链开发教程和文档,帮助开发者快速上手区块链开发。