Flutter中最經常使用的Widget是StatelessWidget
和StatefulWidget
,分別對應於無狀態的組件和有狀態的組件。而StatefulWidget
中更新狀態的方法就是setState(fn)
,調用該方法後,會從新調用StatefulWidget
的build
方法從新構建組件,達到刷新界面的效果。那麼調用setState
方法後,是經過什麼的樣流程走到build
方法的呢?帶着這個疑惑經過閱讀源碼來分析StatefulWidget
的更新流程。node
setState
方法有一個fn
參數,通常會在該函數中執行更新狀態的操做,在方法體內會首先同步執行fn
函數。這個函數的返回值不能是Future
類型,即不能是async
異步函數。執行完fn
函數後,調用_element
的markNeedsBuild
方法。markdown
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
屬性中。app
StatefulElement(StatefulWidget widget)
: _state = widget.createState(),
super(widget) {
...
_state._element = this;
...
_state._widget = widget;
assert(_state._debugLifecycleState == _StateLifecycle.created);
}
複製代碼
void markNeedsBuild() {
...
if (!_active)
return;
...
if (dirty)
return;
_dirty = true;
owner.scheduleBuildFor(this);
}
複製代碼
markNeedsBuild
方法會調用owner
的scheduleBuildFor
方法,將該element
標記爲dirty,而且將element
加入到一個全局的表示須要更新的Element列表中。owner
是BuildOwner
對象。less
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
函數。_dirtyElements
中,而且標記element的_inDirtyList
爲true
,表示已經加入到髒元素列表。經過搜索能夠查到,BuildOwner
是在WdigetBinding
的initInstances
方法中建立的,而且建立完成後設置了onBuildScheduled
回調爲WidgetsBinding的_handleBuildScheduled
方法。因此scheduleBuildFor
方法又會調用到WidgetsBinding
的_handleBuildScheduled
方法。async
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
的相應方法。ide
'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;
}
}
複製代碼
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
請求再次刷新。post
void scheduleFrame() {
if (_hasScheduledFrame || !framesEnabled)
return;
...
ensureFrameCallbacksRegistered();
window.scheduleFrame();
_hasScheduledFrame = true;
}
複製代碼
WidgetBinding
的scheduleFrame
會首先調用ensureFrameCallbacksRegistered
方法確保window
的回調函數以被註冊。再調用window
的scheduleFrame
的方法。ui
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
方法。
@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
方法。
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
操做,以更新顯示狀態。