介绍
Flutter中最常用的Widget是StatelessWidget
和StatefulWidget
,分别对应于无状态的组件和有状态的组件。而StatefulWidget
中更新状态的方法就是setState(fn)
,调用该方法后,会重新调用StatefulWidget
的build
方法重新构建组件,达到刷新界面的效果。那么调用setState
方法后,是通过什么的样流程走到build
方法的呢?带着这个疑惑通过阅读源码来分析StatefulWidget
的更新流程。
源码解析
setState
方法有一个fn
参数,一般会在该函数中执行更新状态的操作,在方法体内会首先同步执行fn
函数。这个函数的返回值不能是Future
类型,即不能是async
异步函数。执行完fn
函数后,调用_element
的markNeedsBuild
方法。
void setState(VoidCallback fn) {
...
final dynamic result = fn() as dynamic;
assert(() {
if (result is Future) {
throw FlutterError.fromParts(<DiagnosticsNode>[
ErrorSummary('setState() callback argument returned a Future.'),
ErrorDescription(
'The setState() method on $this was called with a closure or method that '
'returned a Future. Maybe it is marked as "async".'
),
ErrorHint(
'Instead of performing asynchronous work inside a call to setState(), first '
'execute the work (without updating the widget state), and then synchronously '
'update the state inside a call to setState().'
),
]);
}
return true;
}());
_element.markNeedsBuild();
}
StatefulWidget
对应的Element是StatefulElement
,在StatefulElement
中的构造方法中会通过StatefulWidget
的createState
创建State
,同时将element本身设置给State
的_element
属性。而State
也被保存在Element
的_state
属性中。
StatefulElement(StatefulWidget widget)
: _state = widget.createState(),
super(widget) {
...
_state._element = this;
...
_state._widget = widget;
assert(_state._debugLifecycleState == _StateLifecycle.created);
}
Element markNeedsBuild
void markNeedsBuild() {
...
if (!_active)
return;
...
if (dirty)
return;
_dirty = true;
owner.scheduleBuildFor(this);
}
markNeedsBuild
方法会调用owner
的scheduleBuildFor
方法,将该element
标记为dirty,并且将element
加入到一个全局的表示需要更新的Element列表中。owner
是BuildOwner
对象。
BuildOwner scheduleBuildFor
void scheduleBuildFor(Element element) {
...
if (element._inDirtyList) {
...
_dirtyElementsNeedsResorting = true;
return;
}
if (!_scheduledFlushDirtyElements && onBuildScheduled != null) {
_scheduledFlushDirtyElements = true;
onBuildScheduled();
}
_dirtyElements.add(element);
element._inDirtyList = true;
...
}
这个方法主要执行几个任务
- 判断
element
是否已经加入到_dirtyElements
列表中,如果已经在列表中,就直接返回,不用再执行下面的操作。 - 判断
_scheduledFlushDirtyElements
是否为false
,这个变量表示当前是否正在rebuild_dirtyElements
中的元素。如果没有正在rebuild,并且onBuildScheduled
回调不为空,就调用onBuildScheduled
函数。 - 将element加入到
_dirtyElements
中,并且标记element的_inDirtyList
为true
,表示已经加入到脏元素列表。
通过搜索可以查到,BuildOwner
是在WdigetBinding
的initInstances
方法中创建的,并且创建完成后设置了onBuildScheduled
回调为WidgetsBinding的_handleBuildScheduled
方法。所以scheduleBuildFor
方法又会调用到WidgetsBinding
的_handleBuildScheduled
方法。
WdigetBinding _handleBuildScheduled
mixin WidgetsBinding on BindingBase, ServicesBinding, SchedulerBinding, GestureBinding, RendererBinding, SemanticsBinding {
@override
void initInstances() {
super.initInstances();
_instance = this;
...
// Initialization of [_buildOwner] has to be done after
// [super.initInstances] is called, as it requires [ServicesBinding] to
// properly setup the [defaultBinaryMessenger] instance.
_buildOwner = BuildOwner();
buildOwner.onBuildScheduled = _handleBuildScheduled;
window.onLocaleChanged = handleLocaleChanged;
window.onAccessibilityFeaturesChanged = handleAccessibilityFeaturesChanged;
SystemChannels.navigation.setMethodCallHandler(_handleNavigationInvocation);
FlutterErrorDetails.propertiesTransformers.add(transformDebugCreator);
}
void _handleBuildScheduled() {
// If we're in the process of building dirty elements, then changes
// should not trigger a new frame.
...
ensureVisualUpdate();
}
在_handleBuildScheduled
调用ensureVisualUpdate
,注意,ensureVisualUpdate
并不是WidgetsBinding
中的方法,而是SchedulerBinding
中的方法,WidgetsBinding
和SchedulerBinding
都是mixin
,被集成在WidgetsFlutterBinding
类中,在应用启动执行runApp
函数时会进行初始化。在dart
中,一个类同时引入多个mixin
,根据with
的顺序,最右边的优先级更高。mixin
有个线性化处理,如果右边的mixin
重写了某一方法,并且在重写方法中调用了super.overrideMethod()
,就会调用其左边的mixin
的相应方法。
'Dart中的Mixins通过创建一个新类来实现,该类将mixin的实现层叠在一个超类之上以创建一个新类 ,它不是“在超类中”,而是在超类的“顶部”,因此如何解决查找问题不会产生歧义。
— Lasse R. H. Nielsen on StackOverflow.'
class WidgetsFlutterBinding extends BindingBase with GestureBinding, ServicesBinding, SchedulerBinding, PaintingBinding, SemanticsBinding, RendererBinding, WidgetsBinding {
static WidgetsBinding ensureInitialized() {
if (WidgetsBinding.instance == null)
WidgetsFlutterBinding();
return WidgetsBinding.instance;
}
}
SchedulerBinding scheduleFrame
void ensureVisualUpdate() {
switch (schedulerPhase) {
case SchedulerPhase.idle:
case SchedulerPhase.postFrameCallbacks:
scheduleFrame();
return;
case SchedulerPhase.transientCallbacks:
case SchedulerPhase.midFrameMicrotasks:
case SchedulerPhase.persistentCallbacks:
return;
}
}
ensureVisualUpdate
方法会通过SchedulerPhase
枚举类判断当前的刷新状态。一共有五种状态 状态的转变流程为
transientCallbacks
-> midFrameMicrotasks
-> persistentCallbacks
-> postFrameCallbacks
-> idle
通过后面的分析,可以知道真正的刷新过程是在persistentCallbacks
状态完成的。
所以,如果上次刷新已经完成(postFrameCallbacks
或idle
状态),就会调用scheduleFrame
请求再次刷新。
void scheduleFrame() {
if (_hasScheduledFrame || !framesEnabled)
return;
...
ensureFrameCallbacksRegistered();
window.scheduleFrame();
_hasScheduledFrame = true;
}
WidgetBinding
的scheduleFrame
会首先调用ensureFrameCallbacksRegistered
方法确保window
的回调函数以被注册。再调用window
的scheduleFrame
的方法。
void ensureFrameCallbacksRegistered() {
window.onBeginFrame ??= _handleBeginFrame;
window.onDrawFrame ??= _handleDrawFrame;
}
/// Requests that, at the next appropriate opportunity, the [onBeginFrame]
/// and [onDrawFrame] callbacks be invoked.
void scheduleFrame() native 'Window_scheduleFrame';
Window
的scheduleFrame
方法是个native方法,通过上面的注释,可以知道调用该方法后,onBeginFrame
回调和onDrawFrame
回被调用。这两个回调已经通过ensureFrameCallbacksRegistered
设置为WidgetBinding
的_handleBeginFrame
和_handleDrawFrame
方法。我们重点看下_handleDrawFrame
方法。
void _handleDrawFrame() {
if (_ignoreNextEngineDrawFrame) {
_ignoreNextEngineDrawFrame = false;
return;
}
handleDrawFrame();
}
/// Called by the engine to produce a new frame.
///
/// This method is called immediately after [handleBeginFrame]. It calls all
/// the callbacks registered by [addPersistentFrameCallback], which typically
/// drive the rendering pipeline, and then calls the callbacks registered by
/// [addPostFrameCallback].
void handleDrawFrame() {
...
try {
// PERSISTENT FRAME CALLBACKS
_schedulerPhase = SchedulerPhase.persistentCallbacks;
for (final FrameCallback callback in _persistentCallbacks)
_invokeFrameCallback(callback, _currentFrameTimeStamp);
// POST-FRAME CALLBACKS
_schedulerPhase = SchedulerPhase.postFrameCallbacks;
final List<FrameCallback> localPostFrameCallbacks =
List<FrameCallback>.from(_postFrameCallbacks);
_postFrameCallbacks.clear();
for (final FrameCallback callback in localPostFrameCallbacks)
_invokeFrameCallback(callback, _currentFrameTimeStamp);
} finally {
_schedulerPhase = SchedulerPhase.idle;
...
_currentFrameTimeStamp = null;
}
}
handleDrawFrame
方法上面的注释已经说了该方法的作用,被引擎调用创建一个新的帧。这个方法流程也比较清晰,首先会循环执行_persistentCallbacks
中的callback,这里的callback可以通过WidgetsBinding.instance.addPersistentFrameCallback(fn)
注册;然后,再复制一份_postFrameCallbacks
的拷贝,并将原_postFrameCallbacks
列表清空,_postFrameCallbacks
中保存重绘后执行的回调函数,并且只执行一次,可以通过WidgetsBinding.instance.addPostFrameCallback(fn)
添加回调。执行完_persistentCallbacks
和_postFrameCallbacks
后,便将状态设置为SchedulerPhase.idle
表示已经刷新过。
通过注释可以知道是通过addPersistentFrameCallback
来驱动渲染的。通过搜索,可以看到在RendererBinding
的initInstances
方法中注册了persistentFrameCallback
回调。
mixin RendererBinding on BindingBase, ServicesBinding, SchedulerBinding, GestureBinding, SemanticsBinding, HitTestable {
@override
void initInstances() {
super.initInstances();
...
initRenderView();
_handleSemanticsEnabledChanged();
assert(renderView != null);
addPersistentFrameCallback(_handlePersistentFrameCallback);
initMouseTracker();
}
}
在_handlePersistentFrameCallback
回调函数中直接调用了drawFrame
方法。
void _handlePersistentFrameCallback(Duration timeStamp) {
drawFrame();
_mouseTracker.schedulePostFrameCheck();
}
@protected
void drawFrame() {
assert(renderView != null);
pipelineOwner.flushLayout();
pipelineOwner.flushCompositingBits();
pipelineOwner.flushPaint();
if (sendFramesToEngine) {
renderView.compositeFrame(); // this sends the bits to the GPU
pipelineOwner.flushSemantics(); // this also sends the semantics to the OS.
_firstFrameSent = true;
}
}
需要注意的是,WidgetsBinding
也实现了drawFrame
,并且WidgetsBinding
在被mixin到WidgetsFlutterBinding
类时是在最右边,所以它的方法优先级最高。_handlePersistentFrameCallback
中调用drawFrame
方法时,会先调用WidgetsBinding
中的drawFrame
方法。
WidgetsBinding drawFrame
@override
void drawFrame() {
...
try {
if (renderViewElement != null)
buildOwner.buildScope(renderViewElement);
super.drawFrame();
buildOwner.finalizeTree();
} finally {
assert(() {
debugBuildingDirtyElements = false;
return true;
}());
}
...
}
在WidgetsBinding
的drawFrame
方法中,先调用了buildOwner
的buildScope
方法,然后再调用了super.drawFrame()
,通过super.drawFrame()
可以调用到RendererBinding
的drawFrame
方法。先看buildOwner
的buildScope
方法。
BuildOwner buildScope
void buildScope(Element context, [ VoidCallback callback ]) {
if (callback == null && _dirtyElements.isEmpty)
return;
...
try {
_dirtyElements.sort(Element._sort);
_dirtyElementsNeedsResorting = false;
int dirtyCount = _dirtyElements.length;
int index = 0;
while (index < dirtyCount) {
...
try {
_dirtyElements[index].rebuild();
} catch (e, stack) {
...
}
index += 1;
if (dirtyCount < _dirtyElements.length || _dirtyElementsNeedsResorting) {
_dirtyElements.sort(Element._sort);
_dirtyElementsNeedsResorting = false;
dirtyCount = _dirtyElements.length;
while (index > 0 && _dirtyElements[index - 1].dirty) {
// It is possible for previously dirty but inactive widgets to move right in the list.
// We therefore have to move the index left in the list to account for this.
// We don't know how many could have moved. However, we do know that the only possible
// change to the list is that nodes that were previously to the left of the index have
// now moved to be to the right of the right-most cleaned node, and we do know that
// all the clean nodes were to the left of the index. So we move the index left
// until just after the right-most clean node.
index -= 1;
}
}
}
...
} finally {
for (final Element element in _dirtyElements) {
assert(element._inDirtyList);
element._inDirtyList = false;
}
_dirtyElements.clear();
_scheduledFlushDirtyElements = false;
_dirtyElementsNeedsResorting = null;
...
}
}
buildScope
的核心逻辑就是,首先对_dirtyElements
按照深度进行排序,再遍历_dirtyElements
列表,调用其中元素的rebuild
方法。rebuild
方法定义在Element类中。
void rebuild() {
...
performRebuild();
...
}
@protected
void performRebuild();
performRebuild
是Element
类中的抽象方法,各个子类会实现该方法。StateElement
的父类是ComponentElement
,先看ComponentElement
的performRebuild
方法
@override
void performRebuild() {
...
Widget built;
try {
..
built = build();
..
} catch (e, stack) {
_debugDoingBuild = false;
built = ErrorWidget.builder(
_debugReportException(
ErrorDescription('building $this'),
e,
stack,
informationCollector: () sync* {
yield DiagnosticsDebugCreator(DebugCreator(this));
},
),
);
} finally {
...
}
try {
_child = updateChild(_child, built, slot);
assert(_child != null);
} catch (e, stack) {
...
_child = updateChild(null, built, slot);
}
...
}
在这个方法中,直接调用build
方法创建Widget,如果build
方法产生异常,就会创建一个ErrorWidget
,就是经常看到的红色警告界面。调用完build
方法后,会再调用updateChild(_child, built, slot)
更新子Widget。
StatelessElement
和StatefulElement
重写了build
方法,分别调用了Widget
和State
的build
方法。
///StatelessElement
@override
Widget build() => widget.build(this);
@override
Widget build() => _state.build(this);
前面提到WidgetsBinding
的drawFrame
方法会通过super.drawFrame()
调用到RendererBinding
的drawFrame
方法,再回头看RendererBinding
的drawFrame
方法。
@protected
void drawFrame() {
assert(renderView != null);
pipelineOwner.flushLayout();
pipelineOwner.flushCompositingBits();
pipelineOwner.flushPaint();
if (sendFramesToEngine) {
renderView.compositeFrame(); // this sends the bits to the GPU
pipelineOwner.flushSemantics(); // this also sends the semantics to the OS.
_firstFrameSent = true;
}
}
RendererBinding
的drawFrame
方法,通过pipelineOwner
对象重新layout和paint,已达到更新UI的效果。
总结
StatefulWidget
通过setState
方法将其对应的StatefulElement
添加到BuildOwner
的dirtyElements
中,并触发一次刷新。在收到刷新回调后,遍历dirtyElements
中的元素,执行rebuild
操作,以更新显示状态。