flutter setState的调用链分析

  1. state对象 调用setState方法后,会调用对应的element对象的markNeedsBuild方法,标记当前element为脏的,
  2. 调用BuildOwner对象的方法,把element对象 添加到脏列表中_dirtyElements;
    注意:RendererBinding,注册了 SchedulerBinding对象的 addPersistentFrameCallback 永久帧回调,接收到回调方法时,调用 drawFrame() ,而RendererBinding和WidgetsBinding都有drawFrame方法;所以先调用WidgetsBinding方法 drawFrame()方法;
  3. 最终调用 buildOwner.buildScope()方法 ,遍历 _dirtyElements,调用element的rebuild() 触发widget的重新构建
    关键代码如下:
//mixin RendererBinding{
    void initInstances() {
        addPersistentFrameCallback(_handlePersistentFrameCallback);
    }
    
    void _handlePersistentFrameCallback(Duration timeStamp) {
    drawFrame();
    //...
    }
    
   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;
    }
  }
}
//
mixin WidgetsBinding {
    
    void drawFrame() {
    //...
        if (renderViewElement != null)
        buildOwner.buildScope(renderViewElement);
      super.drawFrame();
    }
}
//
class BuildOwner {
    void buildScope(Element context, [ VoidCallback callback ]) {
            //遍历 _dirtyElements,调用element的rebuild()
         try {
          _dirtyElements[index].rebuild();
        } catch (e, stack) {
    }
}

你可能感兴趣的:(flutter setState的调用链分析)