//主要代码
//第一步
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初始化创建的
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();//确保帧回调已注册
platformDispatcher.scheduleFrame();
}
}
void ensureFrameCallbacksRegistered() {
platformDispatcher.onBeginFrame ??= _handleBeginFrame;
platformDispatcher.onDrawFrame ??= _handleDrawFrame;
}
最终通过widow.scheduleFrame来注册Vsync回调,等带下一个Vsync到来的时候执行handleBeginFrame和handleDrawFrame更新UI