//主要代碼
//第一步
abstract class State<T extends StatefulWidget> with Diagnosticable {
void setState(VoidCallback fn) {
final Object? result = fn() as dynamic;
_element!.markNeedsBuild();
}
}
//主要代碼
//第二步
abstract class Element extends DiagnosticableTree implements BuildContext {
BuildOwner? get owner => _owner;
BuildOwner? _owner;
void markNeedsBuild() {
if (dirty) {
return;
}
_dirty = true;
owner!.scheduleBuildFor(this);
}
}
//第三步 BuildOwner 是在WidgetsBinding初始化創(chuàng)建的
class BuildOwner {
VoidCallback? onBuildScheduled;
/// Adds an element to the dirty elements list so that it will be rebuilt
/// when [WidgetsBinding.drawFrame] calls [buildScope].
void scheduleBuildFor(Element element) {
if (!_scheduledFlushDirtyElements && onBuildScheduled != null) {
_scheduledFlushDirtyElements = true;
onBuildScheduled!();
}
_dirtyElements.add(element);
element._inDirtyList = true;
}
}
//第四步
mixin WidgetsBinding on BindingBase, ServicesBinding, SchedulerBinding, GestureBinding, RendererBinding, SemanticsBinding {
@override
void initInstances() {
super.initInstances();
_instance = this;
_buildOwner = BuildOwner();
buildOwner!.onBuildScheduled = _handleBuildScheduled;
}
void _handleBuildScheduled() {
ensureVisualUpdate();
}
mixin SchedulerBinding on BindingBase {
void ensureVisualUpdate() {
scheduleFrame();
}
void scheduleFrame() {
ensureFrameCallbacksRegistered();//確保幀回調(diào)已注冊(cè)
platformDispatcher.scheduleFrame();
}
}
void ensureFrameCallbacksRegistered() {
platformDispatcher.onBeginFrame ??= _handleBeginFrame;
platformDispatcher.onDrawFrame ??= _handleDrawFrame;
}
最終通過widow.scheduleFrame來注冊(cè)Vsync回調(diào)陌僵,等帶下一個(gè)Vsync到來的時(shí)候執(zhí)行handleBeginFrame和handleDrawFrame更新UI