dart 如何在flutter中建立setState调用?

yxyvkwin  于 2023-06-03  发布在  Flutter
关注(0)|答案(1)|浏览(308)

我知道每次调用setState都会调用build,我想在flutter框架中找到方法链。
所以我检查了flutter的源代码,找到了setState的一些步骤:

  1. _element!.markNeedsBuild()将state的元素标记为dirty。

  1. owner!.scheduleBuildFor(this)调用BuildOwneronBuildScheduled并将元素添加到脏元素列表。

  2. BuildOwneronBuildScheduled被分配到WidgetsBindinginitInstances()中:

1.而WidgetsBindinginitInstances()runApp()中被调用。

我已经仔细检查过了,但是没有看到任何代码调用statebuild方法
setState如何在flutter内部调用build?我们能找到源代码吗?

h7appiyu

h7appiyu1#

handleDrawFrame()中,您可以看到以下部分:

try {
  // PERSISTENT FRAME CALLBACKS
  _schedulerPhase = SchedulerPhase.persistentCallbacks;
  for (final FrameCallback callback in _persistentCallbacks) {
    _invokeFrameCallback(callback, _currentFrameTimeStamp!);
  }

我不知道它被添加到persistenCallbacks的确切位置,但是查看代码中的变量可以看到

/// The persistent callbacks (scheduled by
  /// [SchedulerBinding.addPersistentFrameCallback]) are currently executing.
  ///
  /// Typically, this is the build/layout/paint pipeline. See
  /// [WidgetsBinding.drawFrame] and [SchedulerBinding.handleDrawFrame].
  persistentCallbacks,

这意味着它调用drawFrame
drawFrame中,你会发现这行代码:

buildOwner!.buildScope(rootElement!);

在这个方法中,它查看_dirtyElements中的所有元素。请注意,在scheduleBuildFor中,你在这个问题中发布了它。在这个buildScope中,它调用

element.rebuild();

这反过来又叫

performRebuild():

对于ComponentElements来说

/// Calls the [StatelessWidget.build] method of the [StatelessWidget] object
  /// (for stateless widgets) or the [State.build] method of the [State] object
  /// (for stateful widgets) and then updates the widget tree.
  ///
  /// Called automatically during [mount] to generate the first build, and by
  /// [rebuild] when the element needs updating.
  @override
  @pragma('vm:notify-debugger-on-exception')
  void performRebuild() {

相关问题