關(guān)于構(gòu)造函數(shù)是在父節(jié)點(diǎn)build里調(diào)用的構(gòu)造函數(shù)實例化的子節(jié)點(diǎn)widget冬念,然后父節(jié)點(diǎn)調(diào)用inflateWidget進(jìn)入子節(jié)點(diǎn)的生命周期
inflateWidget
要理解為當(dāng)前的element
為父節(jié)點(diǎn)氢架,調(diào)用inflateWidget
來創(chuàng)建子節(jié)點(diǎn)碌尔,也就是說父節(jié)點(diǎn)的build等流程已經(jīng)走完(build要初始化子節(jié)點(diǎn)實例)
舉例:A 的 child 是 B
Element inflateWidget(Widget newWidget, Object? newSlot) {
//this為A newWidget則是B浇辜,通過Bwidget 創(chuàng)建對應(yīng)的element
final Element newChild = newWidget.createElement();
//新生成的element插入element樹中
newChild.mount(this, newSlot);
return newChild;
}
//可以看到是`createElement`調(diào)起了`widget.createState()`,進(jìn)而`initState`
abstract class StatefulWidget extends Widget {
@override
StatefulElement createElement() => StatefulElement(this);
//...
StatefulElement(StatefulWidget widget)
: _state = widget.createState(),
newChild執(zhí)行該方法 則B element的parent設(shè)置為A券敌,_depth做+1操作
-
ComponentElement重寫Element的mount方法
abstract class Element extends DiagnosticableTree implements BuildContext
_parent = parent;
_depth = _parent != null ? _parent!.depth + 1 : 1;
繼承關(guān)系:
abstract class ComponentElement extends Element
class StatelessElement extends ComponentElement
class StatefulElement extends ComponentElement
abstract class RenderObjectElement extends Element
StatelessElement extends ComponentElement
ComponentElement
重寫Element的mount
,觸發(fā)build
(Element
可沒有build方法)
abstract class ComponentElement extends Element {...
void mount(Element? parent, Object? newSlot) {
super.mount(parent, newSlot);
_firstBuild();
}
-
StatefulElement重寫_firstBuild 方法
StatefulElement
主要是觸發(fā)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