关于构造函数是在父节点build里调用的构造函数实例化的子节点widget,然后父节点调用inflateWidget进入子节点的生命周期
inflateWidget
要理解为当前的element
为父节点,调用inflateWidget
来创建子节点,也就是说父节点的build等流程已经走完(build要初始化子节点实例)
举例:A 的 child 是 B
Element inflateWidget(Widget newWidget, Object? newSlot) {
//this为A newWidget则是B,通过Bwidget 创建对应的element
final Element newChild = newWidget.createElement();
//新生成的element插入element树中
newChild.mount(this, newSlot);
return newChild;
}
//可以看到是`createElement`调起了`widget.createState()`,进而`initState`
abstract class StatefulWidget extends Widget {
@override
StatefulElement createElement() => StatefulElement(this);
//...
StatefulElement(StatefulWidget widget)
: _state = widget.createState(),
newChild执行该方法 则B element的parent设置为A,_depth做+1操作
-
ComponentElement重写Element的mount方法
abstract class Element extends DiagnosticableTree implements BuildContext
_parent = parent;
_depth = _parent != null ? _parent!.depth + 1 : 1;
继承关系:
abstract class ComponentElement extends Element
class StatelessElement extends ComponentElement
class StatefulElement extends ComponentElement
abstract class RenderObjectElement extends Element
StatelessElement extends ComponentElement
ComponentElement
重写Element的mount
,触发build
(Element
可没有build方法)
abstract class ComponentElement extends Element {...
void mount(Element? parent, Object? newSlot) {
super.mount(parent, newSlot);
_firstBuild();
}
-
StatefulElement重写_firstBuild 方法
StatefulElement
主要是触发initState
didChangeDependencies
_firstBuild
void _firstBuild() {
final Object? debugCheckForReturnedFuture = state.initState() as dynamic;
state.didChangeDependencies();
super._firstBuild();
由此可以看出第一次显示时,initState
-> didChangeDependencies
-> _firstBuild
abstract class RenderObjectElement extends Element
重写mount
方法
- ps
stateful...
:inflateWidget
->createElement()
->createState()
->newChild.mount
->_firstBuild
->state.initState()
->state.didChangeDependencies()
->rebuild()
->performRebuild
->updateChild