Flutter开发进阶之瞧瞧State
书接上回
上回说到StatefulWidget
会将自身作为参数创建StatefulElement
,然后StatefulElement的创建过程首先要调用_state = widget.createState()
,会创建并持有一个state通过对其生命周期的管理去对Widget
进行刷新,创建state后还会将自身交给state持有state._element = this;
。
接下来会通过解析State
的构成去理解State
。
首先瞧瞧State
里有些什么?
abstract class State<T extends StatefulWidget> with Diagnosticable {
T get widget => _widget!;
T? _widget;
_StateLifecycle _debugLifecycleState = _StateLifecycle.created;
bool _debugTypesAreRight(Widget widget) => widget is T;
BuildContext get context {
assert(() {
if (_element == null) {
throw FlutterError(
'This widget has been unmounted, so the State no longer has a context (and should be considered defunct). \n'
'Consider canceling any active work during "dispose" or using the "mounted" getter to determine if the State is still active.',
);
}
return true;
}());
return _element!;
}
StatefulElement? _element;
bool get mounted => _element != null;
void initState() {
assert(_debugLifecycleState == _StateLifecycle.created);
if (kFlutterMemoryAllocationsEnabled) {
MemoryAllocations.instance.dispatchObjectCreated(
library: _flutterWidgetsLibrary,
className: '$State',
object: this,
);
}
}
void didUpdateWidget(covariant T oldWidget) {
}
void reassemble() {
}
void setState(VoidCallback fn) {
assert(() {
if (_debugLifecycleState == _StateLi