基于Flutter 1.22.3的源碼刨析柿隙,分析Flutter的StatefulWidget的UI更新機制实撒,相關(guān)源碼:
widgets/framework.dart
widgets/binding.dart
scheduler/binding.dart
lib/ui/window.dart
flutter/runtime/runtime_controller.cc
一、概述
對于Flutter來說扒腕,萬物皆為Widget擂达,常見的Widget子類為StatelessWidget(無狀態(tài))和StatefulWidget(有狀態(tài));
- StatelessWidget:內(nèi)部沒有保存狀態(tài)胶滋,界面創(chuàng)建后不會發(fā)生改變板鬓;
- StatefulWidget:內(nèi)部有保存狀態(tài),當狀態(tài)發(fā)生改變究恤,調(diào)用setState()方法會觸發(fā)StatefulWidget的UI發(fā)生更新俭令,對于自定義繼承自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.
///標記元素為臟元素理张,然后添加到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集合赫蛇,之后會被重建
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)用啟動過程初始化WidgetsBinding時,賦值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是一個enum枚舉類型,有以下5個可取值:
狀態(tài) | 含義 |
---|---|
idle | 沒有正在處理的幀织狐,可能正在執(zhí)行的是WidgetsBinding.scheduleTask暂幼,scheduleMicrotask,Timer移迫,事件handlers旺嬉,或者其他回調(diào)等 |
transientCallbacks | SchedulerBinding.handleBeginFrame過程, 處理動畫狀態(tài)更新 |
midFrameMicrotasks | 處理transientCallbacks階段觸發(fā)的微任務(wù)(Microtasks) |
persistentCallbacks | WidgetsBinding.drawFrame和SchedulerBinding.handleDrawFrame過程厨埋,build/layout/paint流水線工作 |
postFrameCallbacks | 主要是清理和計劃執(zhí)行下一幀的工作 |
2.6 scheduleFrame
void scheduleFrame() {
//只有當APP處于用戶可見狀態(tài)才會準備調(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)接口打交道的核心類邪媳,這里是一個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方法的注冊,“PlatformConfiguration_scheduleFrame”所對應(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)用悲酷,最終會注冊Vsync回調(diào)。 等待下一次vsync信號的到來亲善,然后再經(jīng)過層層調(diào)用最終會調(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的耗時會影響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();
});
//此時階段等于SchedulerPhase.idle;
_hasScheduledFrame = false;
try {
Timeline.startSync('Animate', arguments: timelineWhitelistArguments);
_schedulerPhase = SchedulerPhase.transientCallbacks;
//執(zhí)行動畫的回調(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()來完成添加和刪除成員旷祸,再來簡單看看這兩個方法。
2.10 handleDrawFrame
[-> lib/src/scheduler/binding.dart:: SchedulerBinding]
void handleDrawFrame() {
assert(_schedulerPhase == SchedulerPhase.midFrameMicrotasks);
Timeline.finishSync(); // 標識結(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(); //標識結(jié)束”Frame“階段
profile(() {
_profileFrameStopwatch.stop();
_profileFramePostEvent();
});
_currentFrameTimeStamp = null;
}
}
該方法主要功能:
- 遍歷_persistentCallbacks讼昆,執(zhí)行相應(yīng)的回調(diào)方法托享,可通過addPersistentFrameCallback()注冊,一旦注冊后不可移除浸赫,后續(xù)每一次frame回調(diào)都會執(zhí)行闰围;
- 遍歷_postFrameCallbacks,執(zhí)行相應(yīng)的回調(diào)方法既峡,可通過addPostFrameCallback()注冊羡榴,handleDrawFrame()執(zhí)行完成后會清空_postFrameCallbacks內(nèi)容。
三运敢、小結(jié)
可見校仑,setState()過程主要工作是記錄所有的臟元素,添加到BuildOwner對象的_dirtyElements成員變量传惠,然后調(diào)用scheduleFrame來注冊Vsync回調(diào)迄沫。 當下一次vsync信號的到來時會執(zhí)行handleBeginFrame()和handleDrawFrame()來更新UI。
本文參考了gityan大佬的博客卦方,感謝大佬分享邢滑!