layoutWidget function

Element? layoutWidget(
  1. Widget widget,
  2. Size size,
  3. double? pixelRatio
)

Lays out the provided widget in a view of size and returns it as Element.

Implementation

Element? layoutWidget(Widget widget, Size size, double? pixelRatio) {
  RenderRepaintBoundary repaintBoundary = RenderRepaintBoundary();

  RenderView renderView = RenderView(
    configuration: ViewConfiguration(
      logicalConstraints: BoxConstraints.tight(size),
      physicalConstraints: BoxConstraints.tight(size * (pixelRatio ?? 1.0)),
      devicePixelRatio: pixelRatio ?? 1.0,
    ),
    view: WidgetsBinding.instance.platformDispatcher.views.first,
    child: RenderPositionedBox(
      alignment: Alignment.center,
      child: repaintBoundary,
    ),
  );

  PipelineOwner pipelineOwner = PipelineOwner();
  pipelineOwner.rootNode = renderView;
  renderView.prepareInitialFrame();

  widget = MediaQuery(
    data: MediaQueryData(size: size),
    child: MaterialApp(
      home: Material(
        child: Directionality(
          key: exportFrameKey,
          textDirection: TextDirection.ltr,
          child: widget,
        ),
      ),
    ),
  );

  BuildOwner buildOwner = BuildOwner(focusManager: FocusManager());
  RenderObjectToWidgetElement rootElement = RenderObjectToWidgetAdapter(
    container: repaintBoundary,
    child: widget,
  ).attachToRenderTree(buildOwner);
  buildOwner.buildScope(rootElement);
  buildOwner.finalizeTree();

  pipelineOwner.flushLayout();
  pipelineOwner.flushCompositingBits();
  pipelineOwner.flushPaint();

  Element? element;

  rootElement.visitChildren((Element child) => element = child);

  Element? exportFrameElement = extractExportFrame(element!);

  return exportFrameElement;
}