基于Flutter 1.22.3的源碼刨析,分析Flutter的StatefulWidget的UI更新機(jī)制,相關(guān)源碼:
widgets/framework.dart
widgets/binding.dart
scheduler/binding.dart
lib/ui/window.dart
flutter/runtime/runtime_controller.cc
一、概述
對(duì)于Flutter來說,萬物皆為Widget,常見的Widget子類為StatelessWidget(無狀態(tài))和StatefulWidget(有狀態(tài));
- StatelessWidget:內(nèi)部沒有保存狀態(tài),界面創(chuàng)建后不會(huì)發(fā)生改變;
- StatefulWidget:內(nèi)部有保存狀態(tài),當(dāng)狀態(tài)發(fā)生改變,調(diào)用setState()方法會(huì)觸發(fā)StatefulWidget的UI發(fā)生更新,對(duì)于自定義繼承自StatefulWidget的子類,必須要重寫createState()方法。
接下來看看setState()究竟干了哪些操作。
二、Widget更新流程
2.1 setState
[-> framework.dart::state]
abstract class State<T extends StatefulWidget> with Diagnosticable {
StatefulElement _element;
/// It is an error to call this method after the framework calls [dispose].
/// You can determine whether it is legal to call this method by checking
/// whether the [mounted] property is true.
@protected
void setState(VoidCallback fn) {
...
_element.markNeedsBuild();
}
}
這里需要注意setState()方法要在dispose()方法調(diào)用前調(diào)用,可以通過mounted屬性值來判斷父Widget是否還包含該Widget.
2.2 markNeedsBuild
[->framework.dart::Element]
abstract class Element extends DiagnosticableTree implements BuildContext {
/// Marks the element as dirty and adds it to the global list of widgets to
/// rebuild in the next frame.
///標(biāo)記元素為臟元素,然后添加到list集合里 等下一幀刷新
void markNeedsBuild() {
if (!_active)
return;
if (dirty)
return;
_dirty = true;
owner.scheduleBuildFor(this);
}
}
設(shè)置 Element的 _dirty 為 true
2.3 scheduleBuildFor
[->framework.dart::BuildOwner]
abstract class Element extends DiagnosticableTree implements BuildContext {
/// Adds an element to the dirty elements list so that it will be rebuilt
/// when [WidgetsBinding.drawFrame] calls [buildScope].
void scheduleBuildFor(Element element) {
...
if (element._inDirtyList) { //是否在集合里面
_dirtyElementsNeedsResorting = true;
return;
}
if (!_scheduledFlushDirtyElements && onBuildScheduled != null) {
_scheduledFlushDirtyElements = true;
onBuildScheduled();
}
_dirtyElements.add(element);//記錄所有臟元素
element._inDirtyList = true;
}
}
將element添加到臟element集合,之后會(huì)被重建
2.4 _handleBuildScheduled
[-> binding.dart:: WidgetsBinding]
/// The glue between the widgets layer and the Flutter engine.
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() {
ensureVisualUpdate();
}
在Flutter應(yīng)用啟動(dòng)過程初始化WidgetsBinding時(shí),賦值onBuildScheduled等于_handleBuildScheduled()。
2.5 ensureVisualUpdate
[ -> binding.dart::SchedulerBinding]
mixin SchedulerBinding on BindingBase {
@override
void initInstances() {
super.initInstances();
_instance = this;
}
void ensureVisualUpdate() {
switch (schedulerPhase) {
case SchedulerPhase.idle:
case SchedulerPhase.postFrameCallbacks:
scheduleFrame();
return;
case SchedulerPhase.transientCallbacks:
case SchedulerPhase.midFrameMicrotasks:
case SchedulerPhase.persistentCallbacks:
return;
}
}
schedulerPhase的初始值為SchedulerPhase.idle。SchedulerPhase是一個(gè)enum枚舉類型,有以下5個(gè)可取值:
| 狀態(tài) | 含義 |
|---|---|
| idle | 沒有正在處理的幀,可能正在執(zhí)行的是WidgetsBinding.scheduleTask,scheduleMicrotask,Timer,事件handlers,或者其他回調(diào)等 |
| transientCallbacks | SchedulerBinding.handleBeginFrame過程, 處理動(dòng)畫狀態(tài)更新 |
| midFrameMicrotasks | 處理transientCallbacks階段觸發(fā)的微任務(wù)(Microtasks) |
| persistentCallbacks | WidgetsBinding.drawFrame和SchedulerBinding.handleDrawFrame過程,build/layout/paint流水線工作 |
| postFrameCallbacks | 主要是清理和計(jì)劃執(zhí)行下一幀的工作 |
2.6 scheduleFrame
void scheduleFrame() {
//只有當(dāng)APP處于用戶可見狀態(tài)才會(huì)準(zhǔn)備調(diào)度下一幀方法
if (_hasScheduledFrame || !framesEnabled)
return;
ensureFrameCallbacksRegistered();
window.scheduleFrame();
_hasScheduledFrame = true;
}
2.7 scheduleFrame
[ -> lib/ui/window.dart::Window]
void scheduleFrame() native 'PlatformConfiguration_scheduleFrame';
window是Flutter引擎中跟圖形相關(guān)接口打交道的核心類,這里是一個(gè)native方法
2.7.1 ScheduleFrame(C++)
[->引擎庫 lib/ui/window/platform_configuration.cc]
void ScheduleFrame(Dart_NativeArguments args) {
UIDartState::ThrowIfUIOperationsProhibited();
UIDartState::Current()->platform_configuration()->client()->ScheduleFrame();
}
通過RegisterNatives()完成native方法的注冊(cè),“PlatformConfiguration_scheduleFrame”所對(duì)應(yīng)的native方法如上所示。
2.7.2 RuntimeController::ScheduleFrame
[->runtime/runtime_controller.cc]
// |PlatformConfigurationClient|
void RuntimeController::ScheduleFrame() {
client_.ScheduleFrame();
}
2.7.3 Engine::ScheduleFrame
[->flutter/shell/common/engine.cc]
void Engine::ScheduleFrame(bool regenerate_layer_tree) {
animator_->RequestFrame(regenerate_layer_tree);
}
Engine::ScheduleFrame()經(jīng)過層層調(diào)用,最終會(huì)注冊(cè)Vsync回調(diào)。 等待下一次vsync信號(hào)的到來,然后再經(jīng)過層層調(diào)用最終會(huì)調(diào)用到Window::BeginFrame()。這里不展開解釋了。
2.8 Window::BeginFrame
[-> flutter/lib/ui/window/window.cc]
void Window::BeginFrame(fml::TimePoint frameTime) {
std::shared_ptr<tonic::DartState> dart_state = library_.dart_state().lock();
if (!dart_state)
return;
tonic::DartState::Scope scope(dart_state);
int64_t microseconds = (frameTime - fml::TimePoint()).ToMicroseconds();
DartInvokeField(library_.value(), "_beginFrame",
{
Dart_NewInteger(microseconds),
});
//執(zhí)行MicroTask
UIDartState::Current()->FlushMicrotasksNow();
DartInvokeField(library_.value(), "_drawFrame", {});
}
Window::BeginFrame()過程主要工作:
- 執(zhí)行_beginFrame
- 執(zhí)行FlushMicrotasksNow
- 執(zhí)行_drawFrame
可見,Microtask位于beginFrame和drawFrame之間,那么Microtask的耗時(shí)會(huì)影響ui繪制過程。
2.9handleBeginFrame
[-> lib/src/scheduler/binding.dart:: SchedulerBinding]
void handleBeginFrame(Duration rawTimeStamp) {
Timeline.startSync('Frame', arguments: timelineWhitelistArguments);
_firstRawTimeStampInEpoch ??= rawTimeStamp;
_currentFrameTimeStamp = _adjustForEpoch(rawTimeStamp ?? _lastRawTimeStamp);
if (rawTimeStamp != null)
_lastRawTimeStamp = rawTimeStamp;
profile(() {
_profileFrameNumber += 1;
_profileFrameStopwatch.reset();
_profileFrameStopwatch.start();
});
//此時(shí)階段等于SchedulerPhase.idle;
_hasScheduledFrame = false;
try {
Timeline.startSync('Animate', arguments: timelineWhitelistArguments);
_schedulerPhase = SchedulerPhase.transientCallbacks;
//執(zhí)行動(dòng)畫的回調(diào)方法
final Map<int, _FrameCallbackEntry> callbacks = _transientCallbacks;
_transientCallbacks = <int, _FrameCallbackEntry>{};
callbacks.forEach((int id, _FrameCallbackEntry callbackEntry) {
if (!_removedIds.contains(id))
_invokeFrameCallback(callbackEntry.callback, _currentFrameTimeStamp, callbackEntry.debugStack);
});
_removedIds.clear();
} finally {
_schedulerPhase = SchedulerPhase.midFrameMicrotasks;
}
}
該方法主要功能是遍歷_transientCallbacks,執(zhí)行相應(yīng)的Animate操作,可通過scheduleFrameCallback()/cancelFrameCallbackWithId()來完成添加和刪除成員,再來簡單看看這兩個(gè)方法。
2.10 handleDrawFrame
[-> lib/src/scheduler/binding.dart:: SchedulerBinding]
void handleDrawFrame() {
assert(_schedulerPhase == SchedulerPhase.midFrameMicrotasks);
Timeline.finishSync(); // 標(biāo)識(shí)結(jié)束"Animate"階段
try {
_schedulerPhase = SchedulerPhase.persistentCallbacks;
//執(zhí)行PERSISTENT FRAME回調(diào)
for (FrameCallback callback in _persistentCallbacks)
_invokeFrameCallback(callback, _currentFrameTimeStamp);
_schedulerPhase = SchedulerPhase.postFrameCallbacks;
// 執(zhí)行POST-FRAME回調(diào)
final List<FrameCallback> localPostFrameCallbacks = List<FrameCallback>.from(_postFrameCallbacks);
_postFrameCallbacks.clear();
for (FrameCallback callback in localPostFrameCallbacks)
_invokeFrameCallback(callback, _currentFrameTimeStamp);
} finally {
_schedulerPhase = SchedulerPhase.idle;
Timeline.finishSync(); //標(biāo)識(shí)結(jié)束”Frame“階段
profile(() {
_profileFrameStopwatch.stop();
_profileFramePostEvent();
});
_currentFrameTimeStamp = null;
}
}
該方法主要功能:
- 遍歷_persistentCallbacks,執(zhí)行相應(yīng)的回調(diào)方法,可通過addPersistentFrameCallback()注冊(cè),一旦注冊(cè)后不可移除,后續(xù)每一次frame回調(diào)都會(huì)執(zhí)行;
- 遍歷_postFrameCallbacks,執(zhí)行相應(yīng)的回調(diào)方法,可通過addPostFrameCallback()注冊(cè),handleDrawFrame()執(zhí)行完成后會(huì)清空_postFrameCallbacks內(nèi)容。
三、小結(jié)
可見,setState()過程主要工作是記錄所有的臟元素,添加到BuildOwner對(duì)象的_dirtyElements成員變量,然后調(diào)用scheduleFrame來注冊(cè)Vsync回調(diào)。 當(dāng)下一次vsync信號(hào)的到來時(shí)會(huì)執(zhí)行handleBeginFrame()和handleDrawFrame()來更新UI。
本文參考了gityan大佬的博客,感謝大佬分享!