- Flutter并不是渲染Widget树的,因为每一次build都会重新创建,极其不稳定,因此渲染Widget树是非常浪费性能的
- 并不是所有的Widget都会被独立渲染,只有继承自
RenderObejctWidget
才会创建RenderObject
进行渲染 - Flutter是对Render🌲进行渲染的
1.Widget🌲
- 其实就我们代码中Widget的层级关系,在代码写完后,Widget树就已经确定
- 在我们创建Widget的时候,Widget源码中有一个非常重要的方法
createElement()
/// Inflates this configuration to a concrete instance.
///
/// A given widget can be included in the tree zero or more times. In particular
/// a given widget can be placed in the tree multiple times. Each time a widget
/// is placed in the tree, it is inflated into an [Element], which means a
/// widget that is incorporated into the tree multiple times will be inflated
/// multiple times.
@protected
@factory
Element createElement();
- 意味着在Widget的创建的时候,就会
隐式调用
该方法创建一个Element,并加入到Element🌲 - 也就是说,
Widget与Element一一对应
2.Element🌲
-
createElement
的实现 - 这里有个非常重要的方法
mount
/// Add this element to the tree in the given slot of the given parent.
///
/// The framework calls this function when a newly created element is added to
/// the tree for the first time. Use this method to initialize state that
/// depends on having a parent. State that is independent of the parent can
/// more easily be initialized in the constructor.
///
/// This method transitions the element from the "initial" lifecycle state to
/// the "active" lifecycle state.
///
/// Subclasses that override this method are likely to want to also override
/// [update], [visitChildren], [RenderObjectElement.insertRenderObjectChild],
/// [RenderObjectElement.moveRenderObjectChild], and
/// [RenderObjectElement.removeRenderObjectChild].
///
/// Implementations of this method should start with a call to the inherited
/// method, as in `super.mount(parent, newSlot)`.
@mustCallSuper
void mount(Element? parent, Object? newSlot) {...}
- 通过注释,可以得知一个重要的信息。当一个新的element被创建并且加入到Element🌲中时,该framework会调用该方法
- 此时我们心中可能有点逻辑了
1.创建Widget会隐式的调用createElement
2.createElement后加入Element🌲中后,会立即执行mount方法
- 那么mount方法到底是实现了什么呢?
1.StatelessElement(StatelessWidget)
1.在StatelessWidget源码中找到createElement
StatelessElement createElement() => StatelessElement(this);
2.进入StatelessElement源码发现没有mount方法
3.进入StatelessElement的父类ComponentElement,此时发现惊奇却又意料之中的mount方法
//去掉assert,相当于执行了__firstBuild()
@override
void mount(Element? parent, Object? newSlot) {
super.mount(parent, newSlot);
assert(_child == null);
assert(_lifecycleState == _ElementLifecycle.active);
_firstBuild();
assert(_child != null);
}
-
4.进入__firstBuild()
只调用了rebuild方法
void _firstBuild() {
rebuild();
}
-
5.进入rebuild(此时进入Element,ComponentElement的super)
去除assert,发现只调用了performRebuild方法
void rebuild() {
assert(_lifecycleState != _ElementLifecycle.initial);
if (_lifecycleState != _ElementLifecycle.active || !_dirty)
return;
assert(() {
debugOnRebuildDirtyWidget?.call(this, _debugBuiltOnce);
if (debugPrintRebuildDirtyWidgets) {
if (!_debugBuiltOnce) {
debugPrint('Building $this');
_debugBuiltOnce = true;
} else {
debugPrint('Rebuilding $this');
}
}
return true;
}());
assert(_lifecycleState == _ElementLifecycle.active);
assert(owner!._debugStateLocked);
Element? debugPreviousBuildTarget;
assert(() {
debugPreviousBuildTarget = owner!._debugCurrentBuildTarget;
owner!._debugCurrentBuildTarget = this;
return true;
}());
performRebuild();
assert(() {
assert(owner!._debugCurrentBuildTarget == this);
owner!._debugCurrentBuildTarget = debugPreviousBuildTarget;
return true;
}());
assert(!_dirty);
}
-
6.进入performRebuild
这里没有实现,此时我们在Element里面
@protected
void performRebuild();
-
7.查看上一层(ComponentElement)是否实现了该方法
此时发现ComponentElement实现该方法,并且执行了build()
此时可能有些疑问,我们的每个Widget里也有build方法,是否调用的那个呢?
答案当然不是了,一个Widget一个是Element,类型都是不一样的
void performRebuild() {
if (!kReleaseMode && debugProfileBuildsEnabled)
Timeline.startSync('${widget.runtimeType}', arguments: timelineArgumentsIndicatingLandmarkEvent);
assert(_debugSetAllowIgnoredCallsToMarkNeedsBuild(true));
Widget? built;
try {
assert(() {
_debugDoingBuild = true;
return true;
}());
built = build();
//这里省略了后面的源码
...
}
-
8.继续查看build
这里没有实现,此时我们在ComponentElement
@protected
Widget build();
-
9.向ComponentElement子类寻找build
此时只有一个类了,StatelessElement
@override
Widget build() => widget.build(this);
执行到这里,已经非常的清楚明了。
这里居然在widget执行build方法,同时把自己(StatelessElement)传入进去了
这能印证了在生命周期中对setState源码分析时说到context其实就是element的说法吗?
当然这个说法并不是完全的正确,因为我们当前分析的是StatelessWidget与StatelessElement
总结
主要是调用build方法,将自己(StatelessElement)传出去
2.StatefulElement(StatefulWidget)
1.在StatefulWidget源码中找到createElement
StatefulElement createElement() => StatefulElement(this);
-
2.进入StatefulElement查看,发现构造方法
执行了_state = widget.createState()方法,_state保存在Element中,也就是StatefulWidget里必须实现的createState方法
执行了state._element = this,也就是将element传给state,Widget和State共用同一个Element
执行了state._widget = widget,也就是为什么在State里面可以使用widget
的原因
当你了解到这,或许就可以想得通关于key出现的BUG
StatefulElement(StatefulWidget widget)
: _state = widget.createState(),
super(widget) {
assert(() {
if (!state._debugTypesAreRight(widget)) {
throw FlutterError.fromParts(<DiagnosticsNode>[
ErrorSummary('StatefulWidget.createState must return a subtype of State<${widget.runtimeType}>'),
ErrorDescription(
'The createState function for ${widget.runtimeType} returned a state '
'of type ${state.runtimeType}, which is not a subtype of '
'State<${widget.runtimeType}>, violating the contract for createState.',
),
]);
}
return true;
}());
assert(state._element == null);
state._element = this;
assert(
state._widget == null,
'The createState function for $widget returned an old or invalid state '
'instance: ${state._widget}, which is not null, violating the contract '
'for createState.',
);
state._widget = widget;
assert(state._debugLifecycleState == _StateLifecycle.created);
}
-
3.StatefulElement继承于ComponentElement
因此中间逻辑和StatelessElement一致 -
3.直接跳到StatefulElement的build方法
state执行build方法,同时把自己(StatelessElement)传入进去了,也就是执行了State类中的build方法
印证了在生命周期中对setState源码分析时说到context其实就是element的说法
@override
Widget build() => state.build(this);
总结
创建State,将Element和Widget赋值给Sate,调用build将自己(StatelessElement)传出去
3.RenderObjectElement(这里以Flex
为例)
1.进入Flex源码,发现继承自MultiChildRenderObjectWidget
class Flex extends MultiChildRenderObjectWidget{}
2.进入MultiChildRenderObjectWidget,发现执行createElement
MultiChildRenderObjectElement createElement() => MultiChildRenderObjectElement(this);
3.进入MultiChildRenderObjectElement,发现并没有mount方法
-
4.进入MultiChildRenderObjectElement父类RenderObjectElement,发现了mount方法
这里调用了_renderObject = widget.createRenderObject(this)
创建了一个RenderObject对象
那么这里创建了RenderObject会加入到Render🌲独立渲染吗?
void mount(Element? parent, Object? newSlot) {
super.mount(parent, newSlot);
assert(() {
_debugDoingBuild = true;
return true;
}());
_renderObject = widget.createRenderObject(this);
assert(!_renderObject!.debugDisposed!);
assert(() {
_debugDoingBuild = false;
return true;
}());
assert(() {
_debugUpdateRenderObjectOwner();
return true;
}());
assert(_slot == newSlot);
attachRenderObject(newSlot);
_dirty = false;
}
-
5.这个方法是Widget调用的,首先去Flex查看
发现了createRenderObject的实现,返回了RenderFlex
RenderFlex实际就是继承自RenderBox,RenderBox继承自RenderObject
意思就是这个方法返回了一个RenderObject对象
@override
RenderFlex createRenderObject(BuildContext context) {
return RenderFlex(
direction: direction,
mainAxisAlignment: mainAxisAlignment,
mainAxisSize: mainAxisSize,
crossAxisAlignment: crossAxisAlignment,
textDirection: getEffectiveTextDirection(context),
verticalDirection: verticalDirection,
textBaseline: textBaseline,
clipBehavior: clipBehavior,
);
}
-
6.那么这个方法实现了有什么作用呢?
因为这个方法是继承的,那么我们去找到它的声明 -
7.从Flex以此往上层找createRenderObject
MultiChildRenderObjectWidget没有
RenderobjectWidget有了
创建RenderObject并加入到Render🌲里
/// Creates an instance of the [RenderObject] class that this
/// [RenderObjectWidget] represents, using the configuration described by this
/// [RenderObjectWidget].
///
/// This method should not do anything with the children of the render object.
/// That should instead be handled by the method that overrides
/// [RenderObjectElement.mount] in the object rendered by this object's
/// [createElement] method. See, for example,
/// [SingleChildRenderObjectElement.mount].
@protected
@factory
RenderObject createRenderObject(BuildContext context);
总结
调用createRenderObject,加入Render🌲
3.Render🌲
继承自RenderObjectWidget并且实现createRenderObject方法返回一个RenderObject
Flutter引擎只有对Render🌲渲染
4.待解决,疑惑
1.StatelessWidget和StatefulWidget怎么渲染上去的?
个人感觉肯定是Element又创建了一次Render