"Fossies" - the Fresh Open Source Software Archive

Member "flutter-1.22.4/packages/flutter/lib/src/rendering/object.dart" (13 Nov 2020, 156138 Bytes) of package /linux/misc/flutter-1.22.4.tar.gz:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) Dart source code syntax highlighting (style: standard) with prefixed line numbers and code folding option. Alternatively you can here view or download the uninterpreted source code file.

    1 // Copyright 2014 The Flutter Authors. All rights reserved.
    2 // Use of this source code is governed by a BSD-style license that can be
    3 // found in the LICENSE file.
    4 
    5 import 'dart:developer';
    6 import 'dart:ui' as ui show PictureRecorder;
    7 
    8 import 'package:flutter/animation.dart';
    9 import 'package:flutter/foundation.dart';
   10 import 'package:flutter/gestures.dart';
   11 import 'package:flutter/painting.dart';
   12 import 'package:flutter/semantics.dart';
   13 import 'package:vector_math/vector_math_64.dart';
   14 
   15 import 'binding.dart';
   16 import 'debug.dart';
   17 import 'layer.dart';
   18 
   19 export 'package:flutter/foundation.dart' show FlutterError, InformationCollector, DiagnosticsNode, ErrorSummary, ErrorDescription, ErrorHint, DiagnosticsProperty, StringProperty, DoubleProperty, EnumProperty, FlagProperty, IntProperty, DiagnosticPropertiesBuilder;
   20 export 'package:flutter/gestures.dart' show HitTestEntry, HitTestResult;
   21 export 'package:flutter/painting.dart';
   22 
   23 /// Base class for data associated with a [RenderObject] by its parent.
   24 ///
   25 /// Some render objects wish to store data on their children, such as the
   26 /// children's input parameters to the parent's layout algorithm or the
   27 /// children's position relative to other children.
   28 ///
   29 /// See also:
   30 ///
   31 ///  * [RenderObject.setupParentData], which [RenderObject] subclasses may
   32 ///    override to attach specific types of parent data to children.
   33 class ParentData {
   34   /// Called when the RenderObject is removed from the tree.
   35   @protected
   36   @mustCallSuper
   37   void detach() { }
   38 
   39   @override
   40   String toString() => '<none>';
   41 }
   42 
   43 /// Signature for painting into a [PaintingContext].
   44 ///
   45 /// The `offset` argument is the offset from the origin of the coordinate system
   46 /// of the [PaintingContext.canvas] to the coordinate system of the callee.
   47 ///
   48 /// Used by many of the methods of [PaintingContext].
   49 typedef PaintingContextCallback = void Function(PaintingContext context, Offset offset);
   50 
   51 /// A place to paint.
   52 ///
   53 /// Rather than holding a canvas directly, [RenderObject]s paint using a painting
   54 /// context. The painting context has a [Canvas], which receives the
   55 /// individual draw operations, and also has functions for painting child
   56 /// render objects.
   57 ///
   58 /// When painting a child render object, the canvas held by the painting context
   59 /// can change because the draw operations issued before and after painting the
   60 /// child might be recorded in separate compositing layers. For this reason, do
   61 /// not hold a reference to the canvas across operations that might paint
   62 /// child render objects.
   63 ///
   64 /// New [PaintingContext] objects are created automatically when using
   65 /// [PaintingContext.repaintCompositedChild] and [pushLayer].
   66 class PaintingContext extends ClipContext {
   67 
   68   /// Creates a painting context.
   69   ///
   70   /// Typically only called by [PaintingContext.repaintCompositedChild]
   71   /// and [pushLayer].
   72   @protected
   73   PaintingContext(this._containerLayer, this.estimatedBounds)
   74     : assert(_containerLayer != null),
   75       assert(estimatedBounds != null);
   76 
   77   final ContainerLayer _containerLayer;
   78 
   79   /// An estimate of the bounds within which the painting context's [canvas]
   80   /// will record painting commands. This can be useful for debugging.
   81   ///
   82   /// The canvas will allow painting outside these bounds.
   83   ///
   84   /// The [estimatedBounds] rectangle is in the [canvas] coordinate system.
   85   final Rect estimatedBounds;
   86 
   87   /// Repaint the given render object.
   88   ///
   89   /// The render object must be attached to a [PipelineOwner], must have a
   90   /// composited layer, and must be in need of painting. The render object's
   91   /// layer, if any, is re-used, along with any layers in the subtree that don't
   92   /// need to be repainted.
   93   ///
   94   /// See also:
   95   ///
   96   ///  * [RenderObject.isRepaintBoundary], which determines if a [RenderObject]
   97   ///    has a composited layer.
   98   static void repaintCompositedChild(RenderObject child, { bool debugAlsoPaintedParent = false }) {
   99     assert(child._needsPaint);
  100     _repaintCompositedChild(
  101       child,
  102       debugAlsoPaintedParent: debugAlsoPaintedParent,
  103     );
  104   }
  105 
  106   static void _repaintCompositedChild(
  107     RenderObject child, {
  108     bool debugAlsoPaintedParent = false,
  109     PaintingContext? childContext,
  110   }) {
  111     assert(child.isRepaintBoundary);
  112     assert(() {
  113       // register the call for RepaintBoundary metrics
  114       child.debugRegisterRepaintBoundaryPaint(
  115         includedParent: debugAlsoPaintedParent,
  116         includedChild: true,
  117       );
  118       return true;
  119     }());
  120     OffsetLayer? childLayer = child._layer as OffsetLayer?;
  121     if (childLayer == null) {
  122       assert(debugAlsoPaintedParent);
  123       // Not using the `layer` setter because the setter asserts that we not
  124       // replace the layer for repaint boundaries. That assertion does not
  125       // apply here because this is exactly the place designed to create a
  126       // layer for repaint boundaries.
  127       child._layer = childLayer = OffsetLayer();
  128     } else {
  129       assert(childLayer is OffsetLayer);
  130       assert(debugAlsoPaintedParent || childLayer.attached);
  131       childLayer.removeAllChildren();
  132     }
  133     assert(identical(childLayer, child._layer));
  134     assert(child._layer is OffsetLayer);
  135     assert(() {
  136       child._layer!.debugCreator = child.debugCreator ?? child.runtimeType;
  137       return true;
  138     }());
  139     childContext ??= PaintingContext(child._layer!, child.paintBounds);
  140     child._paintWithContext(childContext, Offset.zero);
  141 
  142     // Double-check that the paint method did not replace the layer (the first
  143     // check is done in the [layer] setter itself).
  144     assert(identical(childLayer, child._layer));
  145     childContext.stopRecordingIfNeeded();
  146   }
  147 
  148   /// In debug mode, repaint the given render object using a custom painting
  149   /// context that can record the results of the painting operation in addition
  150   /// to performing the regular paint of the child.
  151   ///
  152   /// See also:
  153   ///
  154   ///  * [repaintCompositedChild], for repainting a composited child without
  155   ///    instrumentation.
  156   static void debugInstrumentRepaintCompositedChild(
  157     RenderObject child, {
  158     bool debugAlsoPaintedParent = false,
  159     required PaintingContext customContext,
  160   }) {
  161     assert(() {
  162       _repaintCompositedChild(
  163         child,
  164         debugAlsoPaintedParent: debugAlsoPaintedParent,
  165         childContext: customContext,
  166       );
  167       return true;
  168     }());
  169   }
  170 
  171   /// Paint a child [RenderObject].
  172   ///
  173   /// If the child has its own composited layer, the child will be composited
  174   /// into the layer subtree associated with this painting context. Otherwise,
  175   /// the child will be painted into the current PictureLayer for this context.
  176   void paintChild(RenderObject child, Offset offset) {
  177     assert(() {
  178       if (debugProfilePaintsEnabled)
  179         Timeline.startSync('${child.runtimeType}', arguments: timelineArgumentsIndicatingLandmarkEvent);
  180       if (debugOnProfilePaint != null)
  181         debugOnProfilePaint!(child);
  182       return true;
  183     }());
  184 
  185     if (child.isRepaintBoundary) {
  186       stopRecordingIfNeeded();
  187       _compositeChild(child, offset);
  188     } else {
  189       child._paintWithContext(this, offset);
  190     }
  191 
  192     assert(() {
  193       if (debugProfilePaintsEnabled)
  194         Timeline.finishSync();
  195       return true;
  196     }());
  197   }
  198 
  199   void _compositeChild(RenderObject child, Offset offset) {
  200     assert(!_isRecording);
  201     assert(child.isRepaintBoundary);
  202     assert(_canvas == null || _canvas!.getSaveCount() == 1);
  203 
  204     // Create a layer for our child, and paint the child into it.
  205     if (child._needsPaint) {
  206       repaintCompositedChild(child, debugAlsoPaintedParent: true);
  207     } else {
  208       assert(() {
  209         // register the call for RepaintBoundary metrics
  210         child.debugRegisterRepaintBoundaryPaint(
  211           includedParent: true,
  212           includedChild: false,
  213         );
  214         child._layer!.debugCreator = child.debugCreator ?? child;
  215         return true;
  216       }());
  217     }
  218     assert(child._layer is OffsetLayer);
  219     final OffsetLayer childOffsetLayer = child._layer as OffsetLayer;
  220     childOffsetLayer.offset = offset;
  221     appendLayer(child._layer!);
  222   }
  223 
  224   /// Adds a layer to the recording requiring that the recording is already
  225   /// stopped.
  226   ///
  227   /// Do not call this function directly: call [addLayer] or [pushLayer]
  228   /// instead. This function is called internally when all layers not
  229   /// generated from the [canvas] are added.
  230   ///
  231   /// Subclasses that need to customize how layers are added should override
  232   /// this method.
  233   @protected
  234   void appendLayer(Layer layer) {
  235     assert(!_isRecording);
  236     layer.remove();
  237     _containerLayer.append(layer);
  238   }
  239 
  240   bool get _isRecording {
  241     final bool hasCanvas = _canvas != null;
  242     assert(() {
  243       if (hasCanvas) {
  244         assert(_currentLayer != null);
  245         assert(_recorder != null);
  246         assert(_canvas != null);
  247       } else {
  248         assert(_currentLayer == null);
  249         assert(_recorder == null);
  250         assert(_canvas == null);
  251       }
  252       return true;
  253     }());
  254     return hasCanvas;
  255   }
  256 
  257   // Recording state
  258   PictureLayer? _currentLayer;
  259   ui.PictureRecorder? _recorder;
  260   Canvas? _canvas;
  261 
  262   /// The canvas on which to paint.
  263   ///
  264   /// The current canvas can change whenever you paint a child using this
  265   /// context, which means it's fragile to hold a reference to the canvas
  266   /// returned by this getter.
  267   @override
  268   Canvas get canvas {
  269     if (_canvas == null)
  270       _startRecording();
  271     return _canvas!;
  272   }
  273 
  274   void _startRecording() {
  275     assert(!_isRecording);
  276     _currentLayer = PictureLayer(estimatedBounds);
  277     _recorder = ui.PictureRecorder();
  278     _canvas = Canvas(_recorder!);
  279     _containerLayer.append(_currentLayer!);
  280   }
  281 
  282   /// Stop recording to a canvas if recording has started.
  283   ///
  284   /// Do not call this function directly: functions in this class will call
  285   /// this method as needed. This function is called internally to ensure that
  286   /// recording is stopped before adding layers or finalizing the results of a
  287   /// paint.
  288   ///
  289   /// Subclasses that need to customize how recording to a canvas is performed
  290   /// should override this method to save the results of the custom canvas
  291   /// recordings.
  292   @protected
  293   @mustCallSuper
  294   void stopRecordingIfNeeded() {
  295     if (!_isRecording)
  296       return;
  297     assert(() {
  298       if (debugRepaintRainbowEnabled) {
  299         final Paint paint = Paint()
  300           ..style = PaintingStyle.stroke
  301           ..strokeWidth = 6.0
  302           ..color = debugCurrentRepaintColor.toColor();
  303         canvas.drawRect(estimatedBounds.deflate(3.0), paint);
  304       }
  305       if (debugPaintLayerBordersEnabled) {
  306         final Paint paint = Paint()
  307           ..style = PaintingStyle.stroke
  308           ..strokeWidth = 1.0
  309           ..color = const Color(0xFFFF9800);
  310         canvas.drawRect(estimatedBounds, paint);
  311       }
  312       return true;
  313     }());
  314     _currentLayer!.picture = _recorder!.endRecording();
  315     _currentLayer = null;
  316     _recorder = null;
  317     _canvas = null;
  318   }
  319 
  320   /// Hints that the painting in the current layer is complex and would benefit
  321   /// from caching.
  322   ///
  323   /// If this hint is not set, the compositor will apply its own heuristics to
  324   /// decide whether the current layer is complex enough to benefit from
  325   /// caching.
  326   void setIsComplexHint() {
  327     _currentLayer?.isComplexHint = true;
  328   }
  329 
  330   /// Hints that the painting in the current layer is likely to change next frame.
  331   ///
  332   /// This hint tells the compositor not to cache the current layer because the
  333   /// cache will not be used in the future. If this hint is not set, the
  334   /// compositor will apply its own heuristics to decide whether the current
  335   /// layer is likely to be reused in the future.
  336   void setWillChangeHint() {
  337     _currentLayer?.willChangeHint = true;
  338   }
  339 
  340   /// Adds a composited leaf layer to the recording.
  341   ///
  342   /// After calling this function, the [canvas] property will change to refer to
  343   /// a new [Canvas] that draws on top of the given layer.
  344   ///
  345   /// A [RenderObject] that uses this function is very likely to require its
  346   /// [RenderObject.alwaysNeedsCompositing] property to return true. That informs
  347   /// ancestor render objects that this render object will include a composited
  348   /// layer, which, for example, causes them to use composited clips.
  349   ///
  350   /// See also:
  351   ///
  352   ///  * [pushLayer], for adding a layer and painting further contents within
  353   ///    it.
  354   void addLayer(Layer layer) {
  355     stopRecordingIfNeeded();
  356     appendLayer(layer);
  357   }
  358 
  359   /// Appends the given layer to the recording, and calls the `painter` callback
  360   /// with that layer, providing the `childPaintBounds` as the estimated paint
  361   /// bounds of the child. The `childPaintBounds` can be used for debugging but
  362   /// have no effect on painting.
  363   ///
  364   /// The given layer must be an unattached orphan. (Providing a newly created
  365   /// object, rather than reusing an existing layer, satisfies that
  366   /// requirement.)
  367   ///
  368   /// {@template flutter.rendering.object.pushLayer.offset}
  369   /// The `offset` is the offset to pass to the `painter`. In particular, it is
  370   /// not an offset applied to the layer itself. Layers conceptually by default
  371   /// have no position or size, though they can transform their contents. For
  372   /// example, an [OffsetLayer] applies an offset to its children.
  373   /// {@endtemplate}
  374   ///
  375   /// If the `childPaintBounds` are not specified then the current layer's paint
  376   /// bounds are used. This is appropriate if the child layer does not apply any
  377   /// transformation or clipping to its contents. The `childPaintBounds`, if
  378   /// specified, must be in the coordinate system of the new layer (i.e. as seen
  379   /// by its children after it applies whatever transform to its contents), and
  380   /// should not go outside the current layer's paint bounds.
  381   ///
  382   /// See also:
  383   ///
  384   ///  * [addLayer], for pushing a layer without painting further contents
  385   ///    within it.
  386   void pushLayer(ContainerLayer childLayer, PaintingContextCallback painter, Offset offset, { Rect? childPaintBounds }) {
  387     assert(painter != null);
  388     // If a layer is being reused, it may already contain children. We remove
  389     // them so that `painter` can add children that are relevant for this frame.
  390     if (childLayer.hasChildren) {
  391       childLayer.removeAllChildren();
  392     }
  393     stopRecordingIfNeeded();
  394     appendLayer(childLayer);
  395     final PaintingContext childContext = createChildContext(childLayer, childPaintBounds ?? estimatedBounds);
  396     painter(childContext, offset);
  397     childContext.stopRecordingIfNeeded();
  398   }
  399 
  400   /// Creates a painting context configured to paint into [childLayer].
  401   ///
  402   /// The `bounds` are estimated paint bounds for debugging purposes.
  403   @protected
  404   PaintingContext createChildContext(ContainerLayer childLayer, Rect bounds) {
  405     return PaintingContext(childLayer, bounds);
  406   }
  407 
  408   /// Clip further painting using a rectangle.
  409   ///
  410   /// {@template flutter.rendering.object.needsCompositing}
  411   /// The `needsCompositing` argument specifies whether the child needs
  412   /// compositing. Typically this matches the value of
  413   /// [RenderObject.needsCompositing] for the caller. If false, this method
  414   /// returns null, indicating that a layer is no longer necessary. If a render
  415   /// object calling this method stores the `oldLayer` in its
  416   /// [RenderObject.layer] field, it should set that field to null.
  417   ///
  418   /// When `needsCompositing` is false, this method will use a more efficient
  419   /// way to apply the layer effect than actually creating a layer.
  420   /// {@endtemplate}
  421   ///
  422   /// {@template flutter.rendering.object.pushClipLayer.offset}
  423   /// The `offset` argument is the offset from the origin of the canvas'
  424   /// coordinate system to the origin of the caller's coordinate system.
  425   /// {@endtemplate}
  426   ///
  427   /// The `clipRect` is the rectangle (in the caller's coordinate system) to use
  428   /// to clip the painting done by [painter]. It should not include the
  429   /// `offset`.
  430   ///
  431   /// The `painter` callback will be called while the `clipRect` is applied. It
  432   /// is called synchronously during the call to [pushClipRect].
  433   ///
  434   /// The `clipBehavior` argument controls how the rectangle is clipped.
  435   ///
  436   /// {@template flutter.rendering.object.oldLayer}
  437   /// For the `oldLayer` argument, specify the layer created in the previous
  438   /// frame. This gives the engine more information for performance
  439   /// optimizations. Typically this is the value of [RenderObject.layer] that a
  440   /// render object creates once, then reuses for all subsequent frames until a
  441   /// layer is no longer needed (e.g. the render object no longer needs
  442   /// compositing) or until the render object changes the type of the layer
  443   /// (e.g. from opacity layer to a clip rect layer).
  444   /// {@endtemplate}
  445   ClipRectLayer? pushClipRect(bool needsCompositing, Offset offset, Rect clipRect, PaintingContextCallback painter, { Clip clipBehavior = Clip.hardEdge, ClipRectLayer? oldLayer }) {
  446     final Rect offsetClipRect = clipRect.shift(offset);
  447     if (needsCompositing) {
  448       final ClipRectLayer layer = oldLayer ?? ClipRectLayer();
  449       layer
  450         ..clipRect = offsetClipRect
  451         ..clipBehavior = clipBehavior;
  452       pushLayer(layer, painter, offset, childPaintBounds: offsetClipRect);
  453       return layer;
  454     } else {
  455       clipRectAndPaint(offsetClipRect, clipBehavior, offsetClipRect, () => painter(this, offset));
  456       return null;
  457     }
  458   }
  459 
  460   /// Clip further painting using a rounded rectangle.
  461   ///
  462   /// {@macro flutter.rendering.object.needsCompositing}
  463   ///
  464   /// {@macro flutter.rendering.object.pushClipLayer.offset}
  465   ///
  466   /// The `bounds` argument is used to specify the region of the canvas (in the
  467   /// caller's coordinate system) into which `painter` will paint.
  468   ///
  469   /// The `clipRRect` argument specifies the rounded-rectangle (in the caller's
  470   /// coordinate system) to use to clip the painting done by `painter`. It
  471   /// should not include the `offset`.
  472   ///
  473   /// The `painter` callback will be called while the `clipRRect` is applied. It
  474   /// is called synchronously during the call to [pushClipRRect].
  475   ///
  476   /// The `clipBehavior` argument controls how the rounded rectangle is clipped.
  477   ///
  478   /// {@macro flutter.rendering.object.oldLayer}
  479   ClipRRectLayer? pushClipRRect(bool needsCompositing, Offset offset, Rect bounds, RRect clipRRect, PaintingContextCallback painter, { Clip clipBehavior = Clip.antiAlias, ClipRRectLayer? oldLayer }) {
  480     assert(clipBehavior != null);
  481     final Rect offsetBounds = bounds.shift(offset);
  482     final RRect offsetClipRRect = clipRRect.shift(offset);
  483     if (needsCompositing) {
  484       final ClipRRectLayer layer = oldLayer ?? ClipRRectLayer();
  485       layer
  486         ..clipRRect = offsetClipRRect
  487         ..clipBehavior = clipBehavior;
  488       pushLayer(layer, painter, offset, childPaintBounds: offsetBounds);
  489       return layer;
  490     } else {
  491       clipRRectAndPaint(offsetClipRRect, clipBehavior, offsetBounds, () => painter(this, offset));
  492       return null;
  493     }
  494   }
  495 
  496   /// Clip further painting using a path.
  497   ///
  498   /// {@macro flutter.rendering.object.needsCompositing}
  499   ///
  500   /// {@macro flutter.rendering.object.pushClipLayer.offset}
  501   ///
  502   /// The `bounds` argument is used to specify the region of the canvas (in the
  503   /// caller's coordinate system) into which `painter` will paint.
  504   ///
  505   /// The `clipPath` argument specifies the [Path] (in the caller's coordinate
  506   /// system) to use to clip the painting done by `painter`. It should not
  507   /// include the `offset`.
  508   ///
  509   /// The `painter` callback will be called while the `clipPath` is applied. It
  510   /// is called synchronously during the call to [pushClipPath].
  511   ///
  512   /// The `clipBehavior` argument controls how the path is clipped.
  513   ///
  514   /// {@macro flutter.rendering.object.oldLayer}
  515   ClipPathLayer? pushClipPath(bool needsCompositing, Offset offset, Rect bounds, Path clipPath, PaintingContextCallback painter, { Clip clipBehavior = Clip.antiAlias, ClipPathLayer? oldLayer }) {
  516     assert(clipBehavior != null);
  517     final Rect offsetBounds = bounds.shift(offset);
  518     final Path offsetClipPath = clipPath.shift(offset);
  519     if (needsCompositing) {
  520       final ClipPathLayer layer = oldLayer ?? ClipPathLayer();
  521       layer
  522         ..clipPath = offsetClipPath
  523         ..clipBehavior = clipBehavior;
  524       pushLayer(layer, painter, offset, childPaintBounds: offsetBounds);
  525       return layer;
  526     } else {
  527       clipPathAndPaint(offsetClipPath, clipBehavior, offsetBounds, () => painter(this, offset));
  528       return null;
  529     }
  530   }
  531 
  532   /// Blend further painting with a color filter.
  533   ///
  534   /// {@macro flutter.rendering.object.pushLayer.offset}
  535   ///
  536   /// The `colorFilter` argument is the [ColorFilter] value to use when blending
  537   /// the painting done by `painter`.
  538   ///
  539   /// The `painter` callback will be called while the `colorFilter` is applied.
  540   /// It is called synchronously during the call to [pushColorFilter].
  541   ///
  542   /// {@macro flutter.rendering.object.oldLayer}
  543   ///
  544   /// A [RenderObject] that uses this function is very likely to require its
  545   /// [RenderObject.alwaysNeedsCompositing] property to return true. That informs
  546   /// ancestor render objects that this render object will include a composited
  547   /// layer, which, for example, causes them to use composited clips.
  548   ColorFilterLayer pushColorFilter(Offset offset, ColorFilter colorFilter, PaintingContextCallback painter, { ColorFilterLayer? oldLayer }) {
  549     assert(colorFilter != null);
  550     final ColorFilterLayer layer = oldLayer ?? ColorFilterLayer();
  551     layer.colorFilter = colorFilter;
  552     pushLayer(layer, painter, offset);
  553     return layer;
  554   }
  555 
  556   /// Transform further painting using a matrix.
  557   ///
  558   /// {@macro flutter.rendering.object.needsCompositing}
  559   ///
  560   /// The `offset` argument is the offset to pass to `painter` and the offset to
  561   /// the origin used by `transform`.
  562   ///
  563   /// The `transform` argument is the [Matrix4] with which to transform the
  564   /// coordinate system while calling `painter`. It should not include `offset`.
  565   /// It is applied effectively after applying `offset`.
  566   ///
  567   /// The `painter` callback will be called while the `transform` is applied. It
  568   /// is called synchronously during the call to [pushTransform].
  569   ///
  570   /// {@macro flutter.rendering.object.oldLayer}
  571   TransformLayer? pushTransform(bool needsCompositing, Offset offset, Matrix4 transform, PaintingContextCallback painter, { TransformLayer? oldLayer }) {
  572     final Matrix4 effectiveTransform = Matrix4.translationValues(offset.dx, offset.dy, 0.0)
  573       ..multiply(transform)..translate(-offset.dx, -offset.dy);
  574     if (needsCompositing) {
  575       final TransformLayer layer = oldLayer ?? TransformLayer();
  576       layer.transform = effectiveTransform;
  577       pushLayer(
  578         layer,
  579         painter,
  580         offset,
  581         childPaintBounds: MatrixUtils.inverseTransformRect(effectiveTransform, estimatedBounds),
  582       );
  583       return layer;
  584     } else {
  585       canvas
  586         ..save()
  587         ..transform(effectiveTransform.storage);
  588       painter(this, offset);
  589       canvas.restore();
  590       return null;
  591     }
  592   }
  593 
  594   /// Blend further painting with an alpha value.
  595   ///
  596   /// The `offset` argument indicates an offset to apply to all the children
  597   /// (the rendering created by `painter`).
  598   ///
  599   /// The `alpha` argument is the alpha value to use when blending the painting
  600   /// done by `painter`. An alpha value of 0 means the painting is fully
  601   /// transparent and an alpha value of 255 means the painting is fully opaque.
  602   ///
  603   /// The `painter` callback will be called while the `alpha` is applied. It
  604   /// is called synchronously during the call to [pushOpacity].
  605   ///
  606   /// {@macro flutter.rendering.object.oldLayer}
  607   ///
  608   /// A [RenderObject] that uses this function is very likely to require its
  609   /// [RenderObject.alwaysNeedsCompositing] property to return true. That informs
  610   /// ancestor render objects that this render object will include a composited
  611   /// layer, which, for example, causes them to use composited clips.
  612   OpacityLayer pushOpacity(Offset offset, int alpha, PaintingContextCallback painter, { OpacityLayer? oldLayer }) {
  613     final OpacityLayer layer = oldLayer ?? OpacityLayer();
  614     layer
  615       ..alpha = alpha
  616       ..offset = offset;
  617     pushLayer(layer, painter, Offset.zero);
  618     return layer;
  619   }
  620 
  621   @override
  622   String toString() => '${objectRuntimeType(this, 'PaintingContext')}#$hashCode(layer: $_containerLayer, canvas bounds: $estimatedBounds)';
  623 }
  624 
  625 /// An abstract set of layout constraints.
  626 ///
  627 /// Concrete layout models (such as box) will create concrete subclasses to
  628 /// communicate layout constraints between parents and children.
  629 ///
  630 /// ## Writing a Constraints subclass
  631 ///
  632 /// When creating a new [RenderObject] subclass with a new layout protocol, one
  633 /// will usually need to create a new [Constraints] subclass to express the
  634 /// input to the layout algorithms.
  635 ///
  636 /// A [Constraints] subclass should be immutable (all fields final). There are
  637 /// several members to implement, in addition to whatever fields, constructors,
  638 /// and helper methods one may find useful for a particular layout protocol:
  639 ///
  640 /// * The [isTight] getter, which should return true if the object represents a
  641 ///   case where the [RenderObject] class has no choice for how to lay itself
  642 ///   out. For example, [BoxConstraints] returns true for [isTight] when both
  643 ///   the minimum and maximum widths and the minimum and maximum heights are
  644 ///   equal.
  645 ///
  646 /// * The [isNormalized] getter, which should return true if the object
  647 ///   represents its data in its canonical form. Sometimes, it is possible for
  648 ///   fields to be redundant with each other, such that several different
  649 ///   representations have the same implications. For example, a
  650 ///   [BoxConstraints] instance with its minimum width greater than its maximum
  651 ///   width is equivalent to one where the maximum width is set to that minimum
  652 ///   width (`2<w<1` is equivalent to `2<w<2`, since minimum constraints have
  653 ///   priority). This getter is used by the default implementation of
  654 ///   [debugAssertIsValid].
  655 ///
  656 /// * The [debugAssertIsValid] method, which should assert if there's anything
  657 ///   wrong with the constraints object. (We use this approach rather than
  658 ///   asserting in constructors so that our constructors can be `const` and so
  659 ///   that it is possible to create invalid constraints temporarily while
  660 ///   building valid ones.) See the implementation of
  661 ///   [BoxConstraints.debugAssertIsValid] for an example of the detailed checks
  662 ///   that can be made.
  663 ///
  664 /// * The [==] operator and the [hashCode] getter, so that constraints can be
  665 ///   compared for equality. If a render object is given constraints that are
  666 ///   equal, then the rendering library will avoid laying the object out again
  667 ///   if it is not dirty.
  668 ///
  669 /// * The [toString] method, which should describe the constraints so that they
  670 ///   appear in a usefully readable form in the output of [debugDumpRenderTree].
  671 @immutable
  672 abstract class Constraints {
  673   /// Abstract const constructor. This constructor enables subclasses to provide
  674   /// const constructors so that they can be used in const expressions.
  675   const Constraints();
  676 
  677   /// Whether there is exactly one size possible given these constraints.
  678   bool get isTight;
  679 
  680   /// Whether the constraint is expressed in a consistent manner.
  681   bool get isNormalized;
  682 
  683   /// Asserts that the constraints are valid.
  684   ///
  685   /// This might involve checks more detailed than [isNormalized].
  686   ///
  687   /// For example, the [BoxConstraints] subclass verifies that the constraints
  688   /// are not [double.nan].
  689   ///
  690   /// If the `isAppliedConstraint` argument is true, then even stricter rules
  691   /// are enforced. This argument is set to true when checking constraints that
  692   /// are about to be applied to a [RenderObject] during layout, as opposed to
  693   /// constraints that may be further affected by other constraints. For
  694   /// example, the asserts for verifying the validity of
  695   /// [RenderConstrainedBox.additionalConstraints] do not set this argument, but
  696   /// the asserts for verifying the argument passed to the [RenderObject.layout]
  697   /// method do.
  698   ///
  699   /// The `informationCollector` argument takes an optional callback which is
  700   /// called when an exception is to be thrown. The collected information is
  701   /// then included in the message after the error line.
  702   ///
  703   /// Returns the same as [isNormalized] if asserts are disabled.
  704   bool debugAssertIsValid({
  705     bool isAppliedConstraint = false,
  706     InformationCollector? informationCollector,
  707   }) {
  708     assert(isNormalized);
  709     return isNormalized;
  710   }
  711 }
  712 
  713 /// Signature for a function that is called for each [RenderObject].
  714 ///
  715 /// Used by [RenderObject.visitChildren] and [RenderObject.visitChildrenForSemantics].
  716 ///
  717 /// The `child` argument must not be null.
  718 typedef RenderObjectVisitor = void Function(RenderObject child);
  719 
  720 /// Signature for a function that is called during layout.
  721 ///
  722 /// Used by [RenderObject.invokeLayoutCallback].
  723 typedef LayoutCallback<T extends Constraints> = void Function(T constraints);
  724 
  725 /// A reference to the semantics tree.
  726 ///
  727 /// The framework maintains the semantics tree (used for accessibility and
  728 /// indexing) only when there is at least one client holding an open
  729 /// [SemanticsHandle].
  730 ///
  731 /// The framework notifies the client that it has updated the semantics tree by
  732 /// calling the [listener] callback. When the client no longer needs the
  733 /// semantics tree, the client can call [dispose] on the [SemanticsHandle],
  734 /// which stops these callbacks and closes the [SemanticsHandle]. When all the
  735 /// outstanding [SemanticsHandle] objects are closed, the framework stops
  736 /// updating the semantics tree.
  737 ///
  738 /// To obtain a [SemanticsHandle], call [PipelineOwner.ensureSemantics] on the
  739 /// [PipelineOwner] for the render tree from which you wish to read semantics.
  740 /// You can obtain the [PipelineOwner] using the [RenderObject.owner] property.
  741 class SemanticsHandle {
  742   SemanticsHandle._(PipelineOwner owner, this.listener)
  743       : assert(owner != null),
  744         _owner = owner {
  745     if (listener != null)
  746       _owner.semanticsOwner!.addListener(listener!);
  747   }
  748 
  749   final PipelineOwner _owner;
  750 
  751   /// The callback that will be notified when the semantics tree updates.
  752   final VoidCallback? listener;
  753 
  754   /// Closes the semantics handle and stops calling [listener] when the
  755   /// semantics updates.
  756   ///
  757   /// When all the outstanding [SemanticsHandle] objects for a given
  758   /// [PipelineOwner] are closed, the [PipelineOwner] will stop updating the
  759   /// semantics tree.
  760   @mustCallSuper
  761   void dispose() {
  762     if (listener != null)
  763       _owner.semanticsOwner!.removeListener(listener!);
  764     _owner._didDisposeSemanticsHandle();
  765   }
  766 }
  767 
  768 /// The pipeline owner manages the rendering pipeline.
  769 ///
  770 /// The pipeline owner provides an interface for driving the rendering pipeline
  771 /// and stores the state about which render objects have requested to be visited
  772 /// in each stage of the pipeline. To flush the pipeline, call the following
  773 /// functions in order:
  774 ///
  775 /// 1. [flushLayout] updates any render objects that need to compute their
  776 ///    layout. During this phase, the size and position of each render
  777 ///    object is calculated. Render objects might dirty their painting or
  778 ///    compositing state during this phase.
  779 /// 2. [flushCompositingBits] updates any render objects that have dirty
  780 ///    compositing bits. During this phase, each render object learns whether
  781 ///    any of its children require compositing. This information is used during
  782 ///    the painting phase when selecting how to implement visual effects such as
  783 ///    clipping. If a render object has a composited child, its needs to use a
  784 ///    [Layer] to create the clip in order for the clip to apply to the
  785 ///    composited child (which will be painted into its own [Layer]).
  786 /// 3. [flushPaint] visits any render objects that need to paint. During this
  787 ///    phase, render objects get a chance to record painting commands into
  788 ///    [PictureLayer]s and construct other composited [Layer]s.
  789 /// 4. Finally, if semantics are enabled, [flushSemantics] will compile the
  790 ///    semantics for the render objects. This semantic information is used by
  791 ///    assistive technology to improve the accessibility of the render tree.
  792 ///
  793 /// The [RendererBinding] holds the pipeline owner for the render objects that
  794 /// are visible on screen. You can create other pipeline owners to manage
  795 /// off-screen objects, which can flush their pipelines independently of the
  796 /// on-screen render objects.
  797 class PipelineOwner {
  798   /// Creates a pipeline owner.
  799   ///
  800   /// Typically created by the binding (e.g., [RendererBinding]), but can be
  801   /// created separately from the binding to drive off-screen render objects
  802   /// through the rendering pipeline.
  803   PipelineOwner({
  804     this.onNeedVisualUpdate,
  805     this.onSemanticsOwnerCreated,
  806     this.onSemanticsOwnerDisposed,
  807   });
  808 
  809   /// Called when a render object associated with this pipeline owner wishes to
  810   /// update its visual appearance.
  811   ///
  812   /// Typical implementations of this function will schedule a task to flush the
  813   /// various stages of the pipeline. This function might be called multiple
  814   /// times in quick succession. Implementations should take care to discard
  815   /// duplicate calls quickly.
  816   final VoidCallback? onNeedVisualUpdate;
  817 
  818   /// Called whenever this pipeline owner creates a semantics object.
  819   ///
  820   /// Typical implementations will schedule the creation of the initial
  821   /// semantics tree.
  822   final VoidCallback? onSemanticsOwnerCreated;
  823 
  824   /// Called whenever this pipeline owner disposes its semantics owner.
  825   ///
  826   /// Typical implementations will tear down the semantics tree.
  827   final VoidCallback? onSemanticsOwnerDisposed;
  828 
  829   /// Calls [onNeedVisualUpdate] if [onNeedVisualUpdate] is not null.
  830   ///
  831   /// Used to notify the pipeline owner that an associated render object wishes
  832   /// to update its visual appearance.
  833   void requestVisualUpdate() {
  834     if (onNeedVisualUpdate != null)
  835       onNeedVisualUpdate!();
  836   }
  837 
  838   /// The unique object managed by this pipeline that has no parent.
  839   ///
  840   /// This object does not have to be a [RenderObject].
  841   AbstractNode? get rootNode => _rootNode;
  842   AbstractNode? _rootNode;
  843   set rootNode(AbstractNode? value) {
  844     if (_rootNode == value)
  845       return;
  846     _rootNode?.detach();
  847     _rootNode = value;
  848     _rootNode?.attach(this);
  849   }
  850 
  851   List<RenderObject> _nodesNeedingLayout = <RenderObject>[];
  852 
  853   /// Whether this pipeline is currently in the layout phase.
  854   ///
  855   /// Specifically, whether [flushLayout] is currently running.
  856   ///
  857   /// Only valid when asserts are enabled; in release builds, this
  858   /// always returns false.
  859   bool get debugDoingLayout => _debugDoingLayout;
  860   bool _debugDoingLayout = false;
  861 
  862   /// Update the layout information for all dirty render objects.
  863   ///
  864   /// This function is one of the core stages of the rendering pipeline. Layout
  865   /// information is cleaned prior to painting so that render objects will
  866   /// appear on screen in their up-to-date locations.
  867   ///
  868   /// See [RendererBinding] for an example of how this function is used.
  869   void flushLayout() {
  870     if (!kReleaseMode) {
  871       Timeline.startSync('Layout', arguments: timelineArgumentsIndicatingLandmarkEvent);
  872     }
  873     assert(() {
  874       _debugDoingLayout = true;
  875       return true;
  876     }());
  877     try {
  878       // TODO(ianh): assert that we're not allowing previously dirty nodes to redirty themselves
  879       while (_nodesNeedingLayout.isNotEmpty) {
  880         final List<RenderObject> dirtyNodes = _nodesNeedingLayout;
  881         _nodesNeedingLayout = <RenderObject>[];
  882         for (final RenderObject node in dirtyNodes..sort((RenderObject a, RenderObject b) => a.depth - b.depth)) {
  883           if (node._needsLayout && node.owner == this)
  884             node._layoutWithoutResize();
  885         }
  886       }
  887     } finally {
  888       assert(() {
  889         _debugDoingLayout = false;
  890         return true;
  891       }());
  892       if (!kReleaseMode) {
  893         Timeline.finishSync();
  894       }
  895     }
  896   }
  897 
  898   // This flag is used to allow the kinds of mutations performed by GlobalKey
  899   // reparenting while a LayoutBuilder is being rebuilt and in so doing tries to
  900   // move a node from another LayoutBuilder subtree that hasn't been updated
  901   // yet. To set this, call [_enableMutationsToDirtySubtrees], which is called
  902   // by [RenderObject.invokeLayoutCallback].
  903   bool _debugAllowMutationsToDirtySubtrees = false;
  904 
  905   // See [RenderObject.invokeLayoutCallback].
  906   void _enableMutationsToDirtySubtrees(VoidCallback callback) {
  907     assert(_debugDoingLayout);
  908     bool? oldState;
  909     assert(() {
  910       oldState = _debugAllowMutationsToDirtySubtrees;
  911       _debugAllowMutationsToDirtySubtrees = true;
  912       return true;
  913     }());
  914     try {
  915       callback();
  916     } finally {
  917       assert(() {
  918         _debugAllowMutationsToDirtySubtrees = oldState!;
  919         return true;
  920       }());
  921     }
  922   }
  923 
  924   final List<RenderObject> _nodesNeedingCompositingBitsUpdate = <RenderObject>[];
  925   /// Updates the [RenderObject.needsCompositing] bits.
  926   ///
  927   /// Called as part of the rendering pipeline after [flushLayout] and before
  928   /// [flushPaint].
  929   void flushCompositingBits() {
  930     if (!kReleaseMode) {
  931       Timeline.startSync('Compositing bits');
  932     }
  933     _nodesNeedingCompositingBitsUpdate.sort((RenderObject a, RenderObject b) => a.depth - b.depth);
  934     for (final RenderObject node in _nodesNeedingCompositingBitsUpdate) {
  935       if (node._needsCompositingBitsUpdate && node.owner == this)
  936         node._updateCompositingBits();
  937     }
  938     _nodesNeedingCompositingBitsUpdate.clear();
  939     if (!kReleaseMode) {
  940       Timeline.finishSync();
  941     }
  942   }
  943 
  944   List<RenderObject> _nodesNeedingPaint = <RenderObject>[];
  945 
  946   /// Whether this pipeline is currently in the paint phase.
  947   ///
  948   /// Specifically, whether [flushPaint] is currently running.
  949   ///
  950   /// Only valid when asserts are enabled. In release builds,
  951   /// this always returns false.
  952   bool get debugDoingPaint => _debugDoingPaint;
  953   bool _debugDoingPaint = false;
  954 
  955   /// Update the display lists for all render objects.
  956   ///
  957   /// This function is one of the core stages of the rendering pipeline.
  958   /// Painting occurs after layout and before the scene is recomposited so that
  959   /// scene is composited with up-to-date display lists for every render object.
  960   ///
  961   /// See [RendererBinding] for an example of how this function is used.
  962   void flushPaint() {
  963     if (!kReleaseMode) {
  964       Timeline.startSync('Paint', arguments: timelineArgumentsIndicatingLandmarkEvent);
  965     }
  966     assert(() {
  967       _debugDoingPaint = true;
  968       return true;
  969     }());
  970     try {
  971       final List<RenderObject> dirtyNodes = _nodesNeedingPaint;
  972       _nodesNeedingPaint = <RenderObject>[];
  973       // Sort the dirty nodes in reverse order (deepest first).
  974       for (final RenderObject node in dirtyNodes..sort((RenderObject a, RenderObject b) => b.depth - a.depth)) {
  975         assert(node._layer != null);
  976         if (node._needsPaint && node.owner == this) {
  977           if (node._layer!.attached) {
  978             PaintingContext.repaintCompositedChild(node);
  979           } else {
  980             node._skippedPaintingOnLayer();
  981           }
  982         }
  983       }
  984       assert(_nodesNeedingPaint.isEmpty);
  985     } finally {
  986       assert(() {
  987         _debugDoingPaint = false;
  988         return true;
  989       }());
  990       if (!kReleaseMode) {
  991         Timeline.finishSync();
  992       }
  993     }
  994   }
  995 
  996   /// The object that is managing semantics for this pipeline owner, if any.
  997   ///
  998   /// An owner is created by [ensureSemantics]. The owner is valid for as long
  999   /// there are [SemanticsHandle]s returned by [ensureSemantics] that have not
 1000   /// yet been disposed. Once the last handle has been disposed, the
 1001   /// [semanticsOwner] field will revert to null, and the previous owner will be
 1002   /// disposed.
 1003   ///
 1004   /// When [semanticsOwner] is null, the [PipelineOwner] skips all steps
 1005   /// relating to semantics.
 1006   SemanticsOwner? get semanticsOwner => _semanticsOwner;
 1007   SemanticsOwner? _semanticsOwner;
 1008 
 1009   /// The number of clients registered to listen for semantics.
 1010   ///
 1011   /// The number is increased whenever [ensureSemantics] is called and decreased
 1012   /// when [SemanticsHandle.dispose] is called.
 1013   int get debugOutstandingSemanticsHandles => _outstandingSemanticsHandles;
 1014   int _outstandingSemanticsHandles = 0;
 1015 
 1016   /// Opens a [SemanticsHandle] and calls [listener] whenever the semantics tree
 1017   /// updates.
 1018   ///
 1019   /// The [PipelineOwner] updates the semantics tree only when there are clients
 1020   /// that wish to use the semantics tree. These clients express their interest
 1021   /// by holding [SemanticsHandle] objects that notify them whenever the
 1022   /// semantics tree updates.
 1023   ///
 1024   /// Clients can close their [SemanticsHandle] by calling
 1025   /// [SemanticsHandle.dispose]. Once all the outstanding [SemanticsHandle]
 1026   /// objects for a given [PipelineOwner] are closed, the [PipelineOwner] stops
 1027   /// maintaining the semantics tree.
 1028   SemanticsHandle ensureSemantics({ VoidCallback? listener }) {
 1029     _outstandingSemanticsHandles += 1;
 1030     if (_outstandingSemanticsHandles == 1) {
 1031       assert(_semanticsOwner == null);
 1032       _semanticsOwner = SemanticsOwner();
 1033       if (onSemanticsOwnerCreated != null)
 1034         onSemanticsOwnerCreated!();
 1035     }
 1036     return SemanticsHandle._(this, listener);
 1037   }
 1038 
 1039   void _didDisposeSemanticsHandle() {
 1040     assert(_semanticsOwner != null);
 1041     _outstandingSemanticsHandles -= 1;
 1042     if (_outstandingSemanticsHandles == 0) {
 1043       _semanticsOwner!.dispose();
 1044       _semanticsOwner = null;
 1045       if (onSemanticsOwnerDisposed != null)
 1046         onSemanticsOwnerDisposed!();
 1047     }
 1048   }
 1049 
 1050   bool _debugDoingSemantics = false;
 1051   final Set<RenderObject> _nodesNeedingSemantics = <RenderObject>{};
 1052 
 1053   /// Update the semantics for render objects marked as needing a semantics
 1054   /// update.
 1055   ///
 1056   /// Initially, only the root node, as scheduled by
 1057   /// [RenderObject.scheduleInitialSemantics], needs a semantics update.
 1058   ///
 1059   /// This function is one of the core stages of the rendering pipeline. The
 1060   /// semantics are compiled after painting and only after
 1061   /// [RenderObject.scheduleInitialSemantics] has been called.
 1062   ///
 1063   /// See [RendererBinding] for an example of how this function is used.
 1064   void flushSemantics() {
 1065     if (_semanticsOwner == null)
 1066       return;
 1067     if (!kReleaseMode) {
 1068       Timeline.startSync('Semantics');
 1069     }
 1070     assert(_semanticsOwner != null);
 1071     assert(() {
 1072       _debugDoingSemantics = true;
 1073       return true;
 1074     }());
 1075     try {
 1076       final List<RenderObject> nodesToProcess = _nodesNeedingSemantics.toList()
 1077         ..sort((RenderObject a, RenderObject b) => a.depth - b.depth);
 1078       _nodesNeedingSemantics.clear();
 1079       for (final RenderObject node in nodesToProcess) {
 1080         if (node._needsSemanticsUpdate && node.owner == this)
 1081           node._updateSemantics();
 1082       }
 1083       _semanticsOwner!.sendSemanticsUpdate();
 1084     } finally {
 1085       assert(_nodesNeedingSemantics.isEmpty);
 1086       assert(() {
 1087         _debugDoingSemantics = false;
 1088         return true;
 1089       }());
 1090       if (!kReleaseMode) {
 1091         Timeline.finishSync();
 1092       }
 1093     }
 1094   }
 1095 }
 1096 
 1097 /// An object in the render tree.
 1098 ///
 1099 /// The [RenderObject] class hierarchy is the core of the rendering
 1100 /// library's reason for being.
 1101 ///
 1102 /// [RenderObject]s have a [parent], and have a slot called [parentData] in
 1103 /// which the parent [RenderObject] can store child-specific data, for example,
 1104 /// the child position. The [RenderObject] class also implements the basic
 1105 /// layout and paint protocols.
 1106 ///
 1107 /// The [RenderObject] class, however, does not define a child model (e.g.
 1108 /// whether a node has zero, one, or more children). It also doesn't define a
 1109 /// coordinate system (e.g. whether children are positioned in Cartesian
 1110 /// coordinates, in polar coordinates, etc) or a specific layout protocol (e.g.
 1111 /// whether the layout is width-in-height-out, or constraint-in-size-out, or
 1112 /// whether the parent sets the size and position of the child before or after
 1113 /// the child lays out, etc; or indeed whether the children are allowed to read
 1114 /// their parent's [parentData] slot).
 1115 ///
 1116 /// The [RenderBox] subclass introduces the opinion that the layout
 1117 /// system uses Cartesian coordinates.
 1118 ///
 1119 /// ## Writing a RenderObject subclass
 1120 ///
 1121 /// In most cases, subclassing [RenderObject] itself is overkill, and
 1122 /// [RenderBox] would be a better starting point. However, if a render object
 1123 /// doesn't want to use a Cartesian coordinate system, then it should indeed
 1124 /// inherit from [RenderObject] directly. This allows it to define its own
 1125 /// layout protocol by using a new subclass of [Constraints] rather than using
 1126 /// [BoxConstraints], and by potentially using an entirely new set of objects
 1127 /// and values to represent the result of the output rather than just a [Size].
 1128 /// This increased flexibility comes at the cost of not being able to rely on
 1129 /// the features of [RenderBox]. For example, [RenderBox] implements an
 1130 /// intrinsic sizing protocol that allows you to measure a child without fully
 1131 /// laying it out, in such a way that if that child changes size, the parent
 1132 /// will be laid out again (to take into account the new dimensions of the
 1133 /// child). This is a subtle and bug-prone feature to get right.
 1134 ///
 1135 /// Most aspects of writing a [RenderBox] apply to writing a [RenderObject] as
 1136 /// well, and therefore the discussion at [RenderBox] is recommended background
 1137 /// reading. The main differences are around layout and hit testing, since those
 1138 /// are the aspects that [RenderBox] primarily specializes.
 1139 ///
 1140 /// ### Layout
 1141 ///
 1142 /// A layout protocol begins with a subclass of [Constraints]. See the
 1143 /// discussion at [Constraints] for more information on how to write a
 1144 /// [Constraints] subclass.
 1145 ///
 1146 /// The [performLayout] method should take the [constraints], and apply them.
 1147 /// The output of the layout algorithm is fields set on the object that describe
 1148 /// the geometry of the object for the purposes of the parent's layout. For
 1149 /// example, with [RenderBox] the output is the [RenderBox.size] field. This
 1150 /// output should only be read by the parent if the parent specified
 1151 /// `parentUsesSize` as true when calling [layout] on the child.
 1152 ///
 1153 /// Anytime anything changes on a render object that would affect the layout of
 1154 /// that object, it should call [markNeedsLayout].
 1155 ///
 1156 /// ### Hit Testing
 1157 ///
 1158 /// Hit testing is even more open-ended than layout. There is no method to
 1159 /// override, you are expected to provide one.
 1160 ///
 1161 /// The general behavior of your hit-testing method should be similar to the
 1162 /// behavior described for [RenderBox]. The main difference is that the input
 1163 /// need not be an [Offset]. You are also allowed to use a different subclass of
 1164 /// [HitTestEntry] when adding entries to the [HitTestResult]. When the
 1165 /// [handleEvent] method is called, the same object that was added to the
 1166 /// [HitTestResult] will be passed in, so it can be used to track information
 1167 /// like the precise coordinate of the hit, in whatever coordinate system is
 1168 /// used by the new layout protocol.
 1169 ///
 1170 /// ### Adapting from one protocol to another
 1171 ///
 1172 /// In general, the root of a Flutter render object tree is a [RenderView]. This
 1173 /// object has a single child, which must be a [RenderBox]. Thus, if you want to
 1174 /// have a custom [RenderObject] subclass in the render tree, you have two
 1175 /// choices: you either need to replace the [RenderView] itself, or you need to
 1176 /// have a [RenderBox] that has your class as its child. (The latter is the much
 1177 /// more common case.)
 1178 ///
 1179 /// This [RenderBox] subclass converts from the box protocol to the protocol of
 1180 /// your class.
 1181 ///
 1182 /// In particular, this means that for hit testing it overrides
 1183 /// [RenderBox.hitTest], and calls whatever method you have in your class for
 1184 /// hit testing.
 1185 ///
 1186 /// Similarly, it overrides [performLayout] to create a [Constraints] object
 1187 /// appropriate for your class and passes that to the child's [layout] method.
 1188 ///
 1189 /// ### Layout interactions between render objects
 1190 ///
 1191 /// In general, the layout of a render object should only depend on the output of
 1192 /// its child's layout, and then only if `parentUsesSize` is set to true in the
 1193 /// [layout] call. Furthermore, if it is set to true, the parent must call the
 1194 /// child's [layout] if the child is to be rendered, because otherwise the
 1195 /// parent will not be notified when the child changes its layout outputs.
 1196 ///
 1197 /// It is possible to set up render object protocols that transfer additional
 1198 /// information. For example, in the [RenderBox] protocol you can query your
 1199 /// children's intrinsic dimensions and baseline geometry. However, if this is
 1200 /// done then it is imperative that the child call [markNeedsLayout] on the
 1201 /// parent any time that additional information changes, if the parent used it
 1202 /// in the last layout phase. For an example of how to implement this, see the
 1203 /// [RenderBox.markNeedsLayout] method. It overrides
 1204 /// [RenderObject.markNeedsLayout] so that if a parent has queried the intrinsic
 1205 /// or baseline information, it gets marked dirty whenever the child's geometry
 1206 /// changes.
 1207 abstract class RenderObject extends AbstractNode with DiagnosticableTreeMixin implements HitTestTarget {
 1208   /// Initializes internal fields for subclasses.
 1209   RenderObject() {
 1210     _needsCompositing = isRepaintBoundary || alwaysNeedsCompositing;
 1211   }
 1212 
 1213   /// Cause the entire subtree rooted at the given [RenderObject] to be marked
 1214   /// dirty for layout, paint, etc, so that the effects of a hot reload can be
 1215   /// seen, or so that the effect of changing a global debug flag (such as
 1216   /// [debugPaintSizeEnabled]) can be applied.
 1217   ///
 1218   /// This is called by the [RendererBinding] in response to the
 1219   /// `ext.flutter.reassemble` hook, which is used by development tools when the
 1220   /// application code has changed, to cause the widget tree to pick up any
 1221   /// changed implementations.
 1222   ///
 1223   /// This is expensive and should not be called except during development.
 1224   ///
 1225   /// See also:
 1226   ///
 1227   ///  * [BindingBase.reassembleApplication]
 1228   void reassemble() {
 1229     markNeedsLayout();
 1230     markNeedsCompositingBitsUpdate();
 1231     markNeedsPaint();
 1232     markNeedsSemanticsUpdate();
 1233     visitChildren((RenderObject child) {
 1234       child.reassemble();
 1235     });
 1236   }
 1237 
 1238   // LAYOUT
 1239 
 1240   /// Data for use by the parent render object.
 1241   ///
 1242   /// The parent data is used by the render object that lays out this object
 1243   /// (typically this object's parent in the render tree) to store information
 1244   /// relevant to itself and to any other nodes who happen to know exactly what
 1245   /// the data means. The parent data is opaque to the child.
 1246   ///
 1247   ///  * The parent data field must not be directly set, except by calling
 1248   ///    [setupParentData] on the parent node.
 1249   ///  * The parent data can be set before the child is added to the parent, by
 1250   ///    calling [setupParentData] on the future parent node.
 1251   ///  * The conventions for using the parent data depend on the layout protocol
 1252   ///    used between the parent and child. For example, in box layout, the
 1253   ///    parent data is completely opaque but in sector layout the child is
 1254   ///    permitted to read some fields of the parent data.
 1255   ParentData? parentData;
 1256 
 1257   /// Override to setup parent data correctly for your children.
 1258   ///
 1259   /// You can call this function to set up the parent data for child before the
 1260   /// child is added to the parent's child list.
 1261   void setupParentData(covariant RenderObject child) {
 1262     assert(_debugCanPerformMutations);
 1263     if (child.parentData is! ParentData)
 1264       child.parentData = ParentData();
 1265   }
 1266 
 1267   /// Called by subclasses when they decide a render object is a child.
 1268   ///
 1269   /// Only for use by subclasses when changing their child lists. Calling this
 1270   /// in other cases will lead to an inconsistent tree and probably cause crashes.
 1271   @override
 1272   void adoptChild(RenderObject child) {
 1273     assert(_debugCanPerformMutations);
 1274     assert(child != null);
 1275     setupParentData(child);
 1276     markNeedsLayout();
 1277     markNeedsCompositingBitsUpdate();
 1278     markNeedsSemanticsUpdate();
 1279     super.adoptChild(child);
 1280   }
 1281 
 1282   /// Called by subclasses when they decide a render object is no longer a child.
 1283   ///
 1284   /// Only for use by subclasses when changing their child lists. Calling this
 1285   /// in other cases will lead to an inconsistent tree and probably cause crashes.
 1286   @override
 1287   void dropChild(RenderObject child) {
 1288     assert(_debugCanPerformMutations);
 1289     assert(child != null);
 1290     assert(child.parentData != null);
 1291     child._cleanRelayoutBoundary();
 1292     child.parentData!.detach();
 1293     child.parentData = null;
 1294     super.dropChild(child);
 1295     markNeedsLayout();
 1296     markNeedsCompositingBitsUpdate();
 1297     markNeedsSemanticsUpdate();
 1298   }
 1299 
 1300   /// Calls visitor for each immediate child of this render object.
 1301   ///
 1302   /// Override in subclasses with children and call the visitor for each child.
 1303   void visitChildren(RenderObjectVisitor visitor) { }
 1304 
 1305   /// The object responsible for creating this render object.
 1306   ///
 1307   /// Used in debug messages.
 1308   Object? debugCreator;
 1309 
 1310   void _debugReportException(String method, dynamic exception, StackTrace stack) {
 1311     FlutterError.reportError(FlutterErrorDetails(
 1312       exception: exception,
 1313       stack: stack,
 1314       library: 'rendering library',
 1315       context: ErrorDescription('during $method()'),
 1316       informationCollector: () sync* {
 1317         if (debugCreator != null)
 1318           yield DiagnosticsDebugCreator(debugCreator!);
 1319         yield describeForError('The following RenderObject was being processed when the exception was fired');
 1320         // TODO(jacobr): this error message has a code smell. Consider whether
 1321         // displaying the truncated children is really useful for command line
 1322         // users. Inspector users can see the full tree by clicking on the
 1323         // render object so this may not be that useful.
 1324         yield describeForError('RenderObject', style: DiagnosticsTreeStyle.truncateChildren);
 1325       },
 1326     ));
 1327   }
 1328 
 1329   /// Whether [performResize] for this render object is currently running.
 1330   ///
 1331   /// Only valid when asserts are enabled. In release builds, always returns
 1332   /// false.
 1333   bool get debugDoingThisResize => _debugDoingThisResize;
 1334   bool _debugDoingThisResize = false;
 1335 
 1336   /// Whether [performLayout] for this render object is currently running.
 1337   ///
 1338   /// Only valid when asserts are enabled. In release builds, always returns
 1339   /// false.
 1340   bool get debugDoingThisLayout => _debugDoingThisLayout;
 1341   bool _debugDoingThisLayout = false;
 1342 
 1343   /// The render object that is actively computing layout.
 1344   ///
 1345   /// Only valid when asserts are enabled. In release builds, always returns
 1346   /// null.
 1347   static RenderObject? get debugActiveLayout => _debugActiveLayout;
 1348   static RenderObject? _debugActiveLayout;
 1349 
 1350   /// Whether the parent render object is permitted to use this render object's
 1351   /// size.
 1352   ///
 1353   /// Determined by the `parentUsesSize` parameter to [layout].
 1354   ///
 1355   /// Only valid when asserts are enabled. In release builds, throws.
 1356   bool get debugCanParentUseSize => _debugCanParentUseSize!;
 1357   bool? _debugCanParentUseSize;
 1358 
 1359   bool _debugMutationsLocked = false;
 1360 
 1361   /// Whether tree mutations are currently permitted.
 1362   ///
 1363   /// Only valid when asserts are enabled. In release builds, always returns
 1364   /// null.
 1365   bool get _debugCanPerformMutations {
 1366     late bool result;
 1367     assert(() {
 1368       RenderObject node = this;
 1369       while (true) {
 1370         if (node._doingThisLayoutWithCallback) {
 1371           result = true;
 1372           break;
 1373         }
 1374         if (owner != null && owner!._debugAllowMutationsToDirtySubtrees && node._needsLayout) {
 1375           result = true;
 1376           break;
 1377         }
 1378         if (node._debugMutationsLocked) {
 1379           result = false;
 1380           break;
 1381         }
 1382         if (node.parent is! RenderObject) {
 1383           result = true;
 1384           break;
 1385         }
 1386         node = node.parent as RenderObject;
 1387       }
 1388       return true;
 1389     }());
 1390     return result;
 1391   }
 1392 
 1393   @override
 1394   PipelineOwner? get owner => super.owner as PipelineOwner?;
 1395 
 1396   @override
 1397   void attach(PipelineOwner owner) {
 1398     super.attach(owner);
 1399     // If the node was dirtied in some way while unattached, make sure to add
 1400     // it to the appropriate dirty list now that an owner is available
 1401     if (_needsLayout && _relayoutBoundary != null) {
 1402       // Don't enter this block if we've never laid out at all;
 1403       // scheduleInitialLayout() will handle it
 1404       _needsLayout = false;
 1405       markNeedsLayout();
 1406     }
 1407     if (_needsCompositingBitsUpdate) {
 1408       _needsCompositingBitsUpdate = false;
 1409       markNeedsCompositingBitsUpdate();
 1410     }
 1411     if (_needsPaint && _layer != null) {
 1412       // Don't enter this block if we've never painted at all;
 1413       // scheduleInitialPaint() will handle it
 1414       _needsPaint = false;
 1415       markNeedsPaint();
 1416     }
 1417     if (_needsSemanticsUpdate && _semanticsConfiguration.isSemanticBoundary) {
 1418       // Don't enter this block if we've never updated semantics at all;
 1419       // scheduleInitialSemantics() will handle it
 1420       _needsSemanticsUpdate = false;
 1421       markNeedsSemanticsUpdate();
 1422     }
 1423   }
 1424 
 1425   /// Whether this render object's layout information is dirty.
 1426   ///
 1427   /// This is only set in debug mode. In general, render objects should not need
 1428   /// to condition their runtime behavior on whether they are dirty or not,
 1429   /// since they should only be marked dirty immediately prior to being laid
 1430   /// out and painted. In release builds, this throws.
 1431   ///
 1432   /// It is intended to be used by tests and asserts.
 1433   bool get debugNeedsLayout {
 1434     late bool result;
 1435     assert(() {
 1436       result = _needsLayout;
 1437       return true;
 1438     }());
 1439     return result;
 1440   }
 1441   bool _needsLayout = true;
 1442 
 1443   RenderObject? _relayoutBoundary;
 1444   bool _doingThisLayoutWithCallback = false;
 1445 
 1446   /// The layout constraints most recently supplied by the parent.
 1447   ///
 1448   /// If layout has not yet happened, accessing this getter will
 1449   /// throw a [StateError] exception.
 1450   @protected
 1451   Constraints get constraints {
 1452     if (_constraints == null)
 1453       throw StateError('A RenderObject does not have any constraints before it has been laid out.');
 1454     return _constraints!;
 1455   }
 1456   Constraints? _constraints;
 1457 
 1458   /// Verify that the object's constraints are being met. Override
 1459   /// this function in a subclass to verify that your state matches
 1460   /// the constraints object. This function is only called in checked
 1461   /// mode and only when needsLayout is false. If the constraints are
 1462   /// not met, it should assert or throw an exception.
 1463   @protected
 1464   void debugAssertDoesMeetConstraints();
 1465 
 1466   /// When true, debugAssertDoesMeetConstraints() is currently
 1467   /// executing asserts for verifying the consistent behavior of
 1468   /// intrinsic dimensions methods.
 1469   ///
 1470   /// This should only be set by debugAssertDoesMeetConstraints()
 1471   /// implementations. It is used by tests to selectively ignore
 1472   /// custom layout callbacks. It should not be set outside of
 1473   /// debugAssertDoesMeetConstraints(), and should not be checked in
 1474   /// release mode (where it will always be false).
 1475   static bool debugCheckingIntrinsics = false;
 1476   bool _debugSubtreeRelayoutRootAlreadyMarkedNeedsLayout() {
 1477     if (_relayoutBoundary == null)
 1478       return true; // we don't know where our relayout boundary is yet
 1479     RenderObject node = this;
 1480     while (node != _relayoutBoundary) {
 1481       assert(node._relayoutBoundary == _relayoutBoundary);
 1482       assert(node.parent != null);
 1483       node = node.parent as RenderObject;
 1484       if ((!node._needsLayout) && (!node._debugDoingThisLayout))
 1485         return false;
 1486     }
 1487     assert(node._relayoutBoundary == node);
 1488     return true;
 1489   }
 1490 
 1491   /// Mark this render object's layout information as dirty, and either register
 1492   /// this object with its [PipelineOwner], or defer to the parent, depending on
 1493   /// whether this object is a relayout boundary or not respectively.
 1494   ///
 1495   /// ## Background
 1496   ///
 1497   /// Rather than eagerly updating layout information in response to writes into
 1498   /// a render object, we instead mark the layout information as dirty, which
 1499   /// schedules a visual update. As part of the visual update, the rendering
 1500   /// pipeline updates the render object's layout information.
 1501   ///
 1502   /// This mechanism batches the layout work so that multiple sequential writes
 1503   /// are coalesced, removing redundant computation.
 1504   ///
 1505   /// If a render object's parent indicates that it uses the size of one of its
 1506   /// render object children when computing its layout information, this
 1507   /// function, when called for the child, will also mark the parent as needing
 1508   /// layout. In that case, since both the parent and the child need to have
 1509   /// their layout recomputed, the pipeline owner is only notified about the
 1510   /// parent; when the parent is laid out, it will call the child's [layout]
 1511   /// method and thus the child will be laid out as well.
 1512   ///
 1513   /// Once [markNeedsLayout] has been called on a render object,
 1514   /// [debugNeedsLayout] returns true for that render object until just after
 1515   /// the pipeline owner has called [layout] on the render object.
 1516   ///
 1517   /// ## Special cases
 1518   ///
 1519   /// Some subclasses of [RenderObject], notably [RenderBox], have other
 1520   /// situations in which the parent needs to be notified if the child is
 1521   /// dirtied (e.g., if the child's intrinsic dimensions or baseline changes).
 1522   /// Such subclasses override markNeedsLayout and either call
 1523   /// `super.markNeedsLayout()`, in the normal case, or call
 1524   /// [markParentNeedsLayout], in the case where the parent needs to be laid out
 1525   /// as well as the child.
 1526   ///
 1527   /// If [sizedByParent] has changed, calls
 1528   /// [markNeedsLayoutForSizedByParentChange] instead of [markNeedsLayout].
 1529   void markNeedsLayout() {
 1530     assert(_debugCanPerformMutations);
 1531     if (_needsLayout) {
 1532       assert(_debugSubtreeRelayoutRootAlreadyMarkedNeedsLayout());
 1533       return;
 1534     }
 1535     assert(_relayoutBoundary != null);
 1536     if (_relayoutBoundary != this) {
 1537       markParentNeedsLayout();
 1538     } else {
 1539       _needsLayout = true;
 1540       if (owner != null) {
 1541         assert(() {
 1542           if (debugPrintMarkNeedsLayoutStacks)
 1543             debugPrintStack(label: 'markNeedsLayout() called for $this');
 1544           return true;
 1545         }());
 1546         owner!._nodesNeedingLayout.add(this);
 1547         owner!.requestVisualUpdate();
 1548       }
 1549     }
 1550   }
 1551 
 1552   /// Mark this render object's layout information as dirty, and then defer to
 1553   /// the parent.
 1554   ///
 1555   /// This function should only be called from [markNeedsLayout] or
 1556   /// [markNeedsLayoutForSizedByParentChange] implementations of subclasses that
 1557   /// introduce more reasons for deferring the handling of dirty layout to the
 1558   /// parent. See [markNeedsLayout] for details.
 1559   ///
 1560   /// Only call this if [parent] is not null.
 1561   @protected
 1562   void markParentNeedsLayout() {
 1563     _needsLayout = true;
 1564     assert(this.parent != null);
 1565     final RenderObject parent = this.parent! as RenderObject;
 1566     if (!_doingThisLayoutWithCallback) {
 1567       parent.markNeedsLayout();
 1568     } else {
 1569       assert(parent._debugDoingThisLayout);
 1570     }
 1571     assert(parent == this.parent);
 1572   }
 1573 
 1574   /// Mark this render object's layout information as dirty (like
 1575   /// [markNeedsLayout]), and additionally also handle any necessary work to
 1576   /// handle the case where [sizedByParent] has changed value.
 1577   ///
 1578   /// This should be called whenever [sizedByParent] might have changed.
 1579   ///
 1580   /// Only call this if [parent] is not null.
 1581   void markNeedsLayoutForSizedByParentChange() {
 1582     markNeedsLayout();
 1583     markParentNeedsLayout();
 1584   }
 1585 
 1586   void _cleanRelayoutBoundary() {
 1587     if (_relayoutBoundary != this) {
 1588       _relayoutBoundary = null;
 1589       _needsLayout = true;
 1590       visitChildren(_cleanChildRelayoutBoundary);
 1591     }
 1592   }
 1593 
 1594   // Reduces closure allocation for visitChildren use cases.
 1595   static void _cleanChildRelayoutBoundary(RenderObject child) {
 1596     child._cleanRelayoutBoundary();
 1597   }
 1598 
 1599   /// Bootstrap the rendering pipeline by scheduling the very first layout.
 1600   ///
 1601   /// Requires this render object to be attached and that this render object
 1602   /// is the root of the render tree.
 1603   ///
 1604   /// See [RenderView] for an example of how this function is used.
 1605   void scheduleInitialLayout() {
 1606     assert(attached);
 1607     assert(parent is! RenderObject);
 1608     assert(!owner!._debugDoingLayout);
 1609     assert(_relayoutBoundary == null);
 1610     _relayoutBoundary = this;
 1611     assert(() {
 1612       _debugCanParentUseSize = false;
 1613       return true;
 1614     }());
 1615     owner!._nodesNeedingLayout.add(this);
 1616   }
 1617 
 1618   void _layoutWithoutResize() {
 1619     assert(_relayoutBoundary == this);
 1620     RenderObject? debugPreviousActiveLayout;
 1621     assert(!_debugMutationsLocked);
 1622     assert(!_doingThisLayoutWithCallback);
 1623     assert(_debugCanParentUseSize != null);
 1624     assert(() {
 1625       _debugMutationsLocked = true;
 1626       _debugDoingThisLayout = true;
 1627       debugPreviousActiveLayout = _debugActiveLayout;
 1628       _debugActiveLayout = this;
 1629       if (debugPrintLayouts)
 1630         debugPrint('Laying out (without resize) $this');
 1631       return true;
 1632     }());
 1633     try {
 1634       performLayout();
 1635       markNeedsSemanticsUpdate();
 1636     } catch (e, stack) {
 1637       _debugReportException('performLayout', e, stack);
 1638     }
 1639     assert(() {
 1640       _debugActiveLayout = debugPreviousActiveLayout;
 1641       _debugDoingThisLayout = false;
 1642       _debugMutationsLocked = false;
 1643       return true;
 1644     }());
 1645     _needsLayout = false;
 1646     markNeedsPaint();
 1647   }
 1648 
 1649   /// Compute the layout for this render object.
 1650   ///
 1651   /// This method is the main entry point for parents to ask their children to
 1652   /// update their layout information. The parent passes a constraints object,
 1653   /// which informs the child as to which layouts are permissible. The child is
 1654   /// required to obey the given constraints.
 1655   ///
 1656   /// If the parent reads information computed during the child's layout, the
 1657   /// parent must pass true for `parentUsesSize`. In that case, the parent will
 1658   /// be marked as needing layout whenever the child is marked as needing layout
 1659   /// because the parent's layout information depends on the child's layout
 1660   /// information. If the parent uses the default value (false) for
 1661   /// `parentUsesSize`, the child can change its layout information (subject to
 1662   /// the given constraints) without informing the parent.
 1663   ///
 1664   /// Subclasses should not override [layout] directly. Instead, they should
 1665   /// override [performResize] and/or [performLayout]. The [layout] method
 1666   /// delegates the actual work to [performResize] and [performLayout].
 1667   ///
 1668   /// The parent's [performLayout] method should call the [layout] of all its
 1669   /// children unconditionally. It is the [layout] method's responsibility (as
 1670   /// implemented here) to return early if the child does not need to do any
 1671   /// work to update its layout information.
 1672   void layout(Constraints constraints, { bool parentUsesSize = false }) {
 1673     if (!kReleaseMode && debugProfileLayoutsEnabled)
 1674       Timeline.startSync('$runtimeType',  arguments: timelineArgumentsIndicatingLandmarkEvent);
 1675 
 1676     assert(constraints != null);
 1677     assert(constraints.debugAssertIsValid(
 1678       isAppliedConstraint: true,
 1679       informationCollector: () sync* {
 1680         final List<String> stack = StackTrace.current.toString().split('\n');
 1681         int? targetFrame;
 1682         final Pattern layoutFramePattern = RegExp(r'^#[0-9]+ +RenderObject.layout \(');
 1683         for (int i = 0; i < stack.length; i += 1) {
 1684           if (layoutFramePattern.matchAsPrefix(stack[i]) != null) {
 1685             targetFrame = i + 1;
 1686             break;
 1687           }
 1688         }
 1689         if (targetFrame != null && targetFrame < stack.length) {
 1690           final Pattern targetFramePattern = RegExp(r'^#[0-9]+ +(.+)$');
 1691           final Match? targetFrameMatch = targetFramePattern.matchAsPrefix(stack[targetFrame]);
 1692           final String? problemFunction = (targetFrameMatch != null && targetFrameMatch.groupCount > 0) ? targetFrameMatch.group(1) : stack[targetFrame].trim();
 1693           // TODO(jacobr): this case is similar to displaying a single stack frame.
 1694           yield ErrorDescription(
 1695             "These invalid constraints were provided to $runtimeType's layout() "
 1696             'function by the following function, which probably computed the '
 1697             'invalid constraints in question:\n'
 1698             '  $problemFunction'
 1699           );
 1700         }
 1701       },
 1702     ));
 1703     assert(!_debugDoingThisResize);
 1704     assert(!_debugDoingThisLayout);
 1705     RenderObject? relayoutBoundary;
 1706     if (!parentUsesSize || sizedByParent || constraints.isTight || parent is! RenderObject) {
 1707       relayoutBoundary = this;
 1708     } else {
 1709       relayoutBoundary = (parent as RenderObject)._relayoutBoundary;
 1710     }
 1711     assert(() {
 1712       _debugCanParentUseSize = parentUsesSize;
 1713       return true;
 1714     }());
 1715     if (!_needsLayout && constraints == _constraints && relayoutBoundary == _relayoutBoundary) {
 1716       assert(() {
 1717         // in case parentUsesSize changed since the last invocation, set size
 1718         // to itself, so it has the right internal debug values.
 1719         _debugDoingThisResize = sizedByParent;
 1720         _debugDoingThisLayout = !sizedByParent;
 1721         final RenderObject? debugPreviousActiveLayout = _debugActiveLayout;
 1722         _debugActiveLayout = this;
 1723         debugResetSize();
 1724         _debugActiveLayout = debugPreviousActiveLayout;
 1725         _debugDoingThisLayout = false;
 1726         _debugDoingThisResize = false;
 1727         return true;
 1728       }());
 1729 
 1730       if (!kReleaseMode && debugProfileLayoutsEnabled)
 1731         Timeline.finishSync();
 1732       return;
 1733     }
 1734     _constraints = constraints;
 1735     if (_relayoutBoundary != null && relayoutBoundary != _relayoutBoundary) {
 1736       // The local relayout boundary has changed, must notify children in case
 1737       // they also need updating. Otherwise, they will be confused about what
 1738       // their actual relayout boundary is later.
 1739       visitChildren(_cleanChildRelayoutBoundary);
 1740     }
 1741     _relayoutBoundary = relayoutBoundary;
 1742     assert(!_debugMutationsLocked);
 1743     assert(!_doingThisLayoutWithCallback);
 1744     assert(() {
 1745       _debugMutationsLocked = true;
 1746       if (debugPrintLayouts)
 1747         debugPrint('Laying out (${sizedByParent ? "with separate resize" : "with resize allowed"}) $this');
 1748       return true;
 1749     }());
 1750     if (sizedByParent) {
 1751       assert(() {
 1752         _debugDoingThisResize = true;
 1753         return true;
 1754       }());
 1755       try {
 1756         performResize();
 1757         assert(() {
 1758           debugAssertDoesMeetConstraints();
 1759           return true;
 1760         }());
 1761       } catch (e, stack) {
 1762         _debugReportException('performResize', e, stack);
 1763       }
 1764       assert(() {
 1765         _debugDoingThisResize = false;
 1766         return true;
 1767       }());
 1768     }
 1769     RenderObject? debugPreviousActiveLayout;
 1770     assert(() {
 1771       _debugDoingThisLayout = true;
 1772       debugPreviousActiveLayout = _debugActiveLayout;
 1773       _debugActiveLayout = this;
 1774       return true;
 1775     }());
 1776     try {
 1777       performLayout();
 1778       markNeedsSemanticsUpdate();
 1779       assert(() {
 1780         debugAssertDoesMeetConstraints();
 1781         return true;
 1782       }());
 1783     } catch (e, stack) {
 1784       _debugReportException('performLayout', e, stack);
 1785     }
 1786     assert(() {
 1787       _debugActiveLayout = debugPreviousActiveLayout;
 1788       _debugDoingThisLayout = false;
 1789       _debugMutationsLocked = false;
 1790       return true;
 1791     }());
 1792     _needsLayout = false;
 1793     markNeedsPaint();
 1794 
 1795     if (!kReleaseMode && debugProfileLayoutsEnabled)
 1796       Timeline.finishSync();
 1797   }
 1798 
 1799   /// If a subclass has a "size" (the state controlled by `parentUsesSize`,
 1800   /// whatever it is in the subclass, e.g. the actual `size` property of
 1801   /// [RenderBox]), and the subclass verifies that in checked mode this "size"
 1802   /// property isn't used when [debugCanParentUseSize] isn't set, then that
 1803   /// subclass should override [debugResetSize] to reapply the current values of
 1804   /// [debugCanParentUseSize] to that state.
 1805   @protected
 1806   void debugResetSize() { }
 1807 
 1808   /// Whether the constraints are the only input to the sizing algorithm (in
 1809   /// particular, child nodes have no impact).
 1810   ///
 1811   /// Returning false is always correct, but returning true can be more
 1812   /// efficient when computing the size of this render object because we don't
 1813   /// need to recompute the size if the constraints don't change.
 1814   ///
 1815   /// Typically, subclasses will always return the same value. If the value can
 1816   /// change, then, when it does change, the subclass should make sure to call
 1817   /// [markNeedsLayoutForSizedByParentChange].
 1818   ///
 1819   /// Subclasses that return true must not change the dimensions of this render
 1820   /// object in [performLayout]. Instead, that work should be done by
 1821   /// [performResize].
 1822   @protected
 1823   bool get sizedByParent => false;
 1824 
 1825   /// Updates the render objects size using only the constraints.
 1826   ///
 1827   /// Do not call this function directly: call [layout] instead. This function
 1828   /// is called by [layout] when there is actually work to be done by this
 1829   /// render object during layout. The layout constraints provided by your
 1830   /// parent are available via the [constraints] getter.
 1831   ///
 1832   /// Subclasses that set [sizedByParent] to true should override this method
 1833   /// to compute their size.
 1834   ///
 1835   /// This function is called only if [sizedByParent] is true.
 1836   @protected
 1837   void performResize();
 1838 
 1839   /// Do the work of computing the layout for this render object.
 1840   ///
 1841   /// Do not call this function directly: call [layout] instead. This function
 1842   /// is called by [layout] when there is actually work to be done by this
 1843   /// render object during layout. The layout constraints provided by your
 1844   /// parent are available via the [constraints] getter.
 1845   ///
 1846   /// If [sizedByParent] is true, then this function should not actually change
 1847   /// the dimensions of this render object. Instead, that work should be done by
 1848   /// [performResize]. If [sizedByParent] is false, then this function should
 1849   /// both change the dimensions of this render object and instruct its children
 1850   /// to layout.
 1851   ///
 1852   /// In implementing this function, you must call [layout] on each of your
 1853   /// children, passing true for parentUsesSize if your layout information is
 1854   /// dependent on your child's layout information. Passing true for
 1855   /// parentUsesSize ensures that this render object will undergo layout if the
 1856   /// child undergoes layout. Otherwise, the child can change its layout
 1857   /// information without informing this render object.
 1858   @protected
 1859   void performLayout();
 1860 
 1861   /// Allows mutations to be made to this object's child list (and any
 1862   /// descendants) as well as to any other dirty nodes in the render tree owned
 1863   /// by the same [PipelineOwner] as this object. The `callback` argument is
 1864   /// invoked synchronously, and the mutations are allowed only during that
 1865   /// callback's execution.
 1866   ///
 1867   /// This exists to allow child lists to be built on-demand during layout (e.g.
 1868   /// based on the object's size), and to enable nodes to be moved around the
 1869   /// tree as this happens (e.g. to handle [GlobalKey] reparenting), while still
 1870   /// ensuring that any particular node is only laid out once per frame.
 1871   ///
 1872   /// Calling this function disables a number of assertions that are intended to
 1873   /// catch likely bugs. As such, using this function is generally discouraged.
 1874   ///
 1875   /// This function can only be called during layout.
 1876   @protected
 1877   void invokeLayoutCallback<T extends Constraints>(LayoutCallback<T> callback) {
 1878     assert(_debugMutationsLocked);
 1879     assert(_debugDoingThisLayout);
 1880     assert(!_doingThisLayoutWithCallback);
 1881     _doingThisLayoutWithCallback = true;
 1882     try {
 1883       owner!._enableMutationsToDirtySubtrees(() { callback(constraints as T); });
 1884     } finally {
 1885       _doingThisLayoutWithCallback = false;
 1886     }
 1887   }
 1888 
 1889   /// Rotate this render object (not yet implemented).
 1890   void rotate({
 1891     int? oldAngle, // 0..3
 1892     int? newAngle, // 0..3
 1893     Duration? time,
 1894   }) { }
 1895 
 1896   // when the parent has rotated (e.g. when the screen has been turned
 1897   // 90 degrees), immediately prior to layout() being called for the
 1898   // new dimensions, rotate() is called with the old and new angles.
 1899   // The next time paint() is called, the coordinate space will have
 1900   // been rotated N quarter-turns clockwise, where:
 1901   //    N = newAngle-oldAngle
 1902   // ...but the rendering is expected to remain the same, pixel for
 1903   // pixel, on the output device. Then, the layout() method or
 1904   // equivalent will be called.
 1905 
 1906 
 1907   // PAINTING
 1908 
 1909   /// Whether [paint] for this render object is currently running.
 1910   ///
 1911   /// Only valid when asserts are enabled. In release builds, always returns
 1912   /// false.
 1913   bool get debugDoingThisPaint => _debugDoingThisPaint;
 1914   bool _debugDoingThisPaint = false;
 1915 
 1916   /// The render object that is actively painting.
 1917   ///
 1918   /// Only valid when asserts are enabled. In release builds, always returns
 1919   /// null.
 1920   static RenderObject? get debugActivePaint => _debugActivePaint;
 1921   static RenderObject? _debugActivePaint;
 1922 
 1923   /// Whether this render object repaints separately from its parent.
 1924   ///
 1925   /// Override this in subclasses to indicate that instances of your class ought
 1926   /// to repaint independently. For example, render objects that repaint
 1927   /// frequently might want to repaint themselves without requiring their parent
 1928   /// to repaint.
 1929   ///
 1930   /// If this getter returns true, the [paintBounds] are applied to this object
 1931   /// and all descendants. The framework automatically creates an [OffsetLayer]
 1932   /// and assigns it to the [layer] field. Render objects that declare
 1933   /// themselves as repaint boundaries must not replace the layer created by
 1934   /// the framework.
 1935   ///
 1936   /// Warning: This getter must not change value over the lifetime of this object.
 1937   ///
 1938   /// See [RepaintBoundary] for more information about how repaint boundaries function.
 1939   bool get isRepaintBoundary => false;
 1940 
 1941   /// Called, in checked mode, if [isRepaintBoundary] is true, when either the
 1942   /// this render object or its parent attempt to paint.
 1943   ///
 1944   /// This can be used to record metrics about whether the node should actually
 1945   /// be a repaint boundary.
 1946   void debugRegisterRepaintBoundaryPaint({ bool includedParent = true, bool includedChild = false }) { }
 1947 
 1948   /// Whether this render object always needs compositing.
 1949   ///
 1950   /// Override this in subclasses to indicate that your paint function always
 1951   /// creates at least one composited layer. For example, videos should return
 1952   /// true if they use hardware decoders.
 1953   ///
 1954   /// You must call [markNeedsCompositingBitsUpdate] if the value of this getter
 1955   /// changes. (This is implied when [adoptChild] or [dropChild] are called.)
 1956   @protected
 1957   bool get alwaysNeedsCompositing => false;
 1958 
 1959   /// The compositing layer that this render object uses to repaint.
 1960   ///
 1961   /// If this render object is not a repaint boundary, it is the responsibility
 1962   /// of the [paint] method to populate this field. If [needsCompositing] is
 1963   /// true, this field may be populated with the root-most layer used by the
 1964   /// render object implementation. When repainting, instead of creating a new
 1965   /// layer the render object may update the layer stored in this field for better
 1966   /// performance. It is also OK to leave this field as null and create a new
 1967   /// layer on every repaint, but without the performance benefit. If
 1968   /// [needsCompositing] is false, this field must be set to null either by
 1969   /// never populating this field, or by setting it to null when the value of
 1970   /// [needsCompositing] changes from true to false.
 1971   ///
 1972   /// If this render object is a repaint boundary, the framework automatically
 1973   /// creates an [OffsetLayer] and populates this field prior to calling the
 1974   /// [paint] method. The [paint] method must not replace the value of this
 1975   /// field.
 1976   @protected
 1977   ContainerLayer? get layer {
 1978     assert(!isRepaintBoundary || (_layer == null || _layer is OffsetLayer));
 1979     return _layer;
 1980   }
 1981 
 1982   @protected
 1983   set layer(ContainerLayer? newLayer) {
 1984     assert(
 1985       !isRepaintBoundary,
 1986       'Attempted to set a layer to a repaint boundary render object.\n'
 1987       'The framework creates and assigns an OffsetLayer to a repaint '
 1988       'boundary automatically.',
 1989     );
 1990     _layer = newLayer;
 1991   }
 1992   ContainerLayer? _layer;
 1993 
 1994   /// In debug mode, the compositing layer that this render object uses to repaint.
 1995   ///
 1996   /// This getter is intended for debugging purposes only. In release builds, it
 1997   /// always returns null. In debug builds, it returns the layer even if the layer
 1998   /// is dirty.
 1999   ///
 2000   /// For production code, consider [layer].
 2001   ContainerLayer? get debugLayer {
 2002     ContainerLayer? result;
 2003     assert(() {
 2004       result = _layer;
 2005       return true;
 2006     }());
 2007     return result;
 2008   }
 2009 
 2010   bool _needsCompositingBitsUpdate = false; // set to true when a child is added
 2011   /// Mark the compositing state for this render object as dirty.
 2012   ///
 2013   /// This is called to indicate that the value for [needsCompositing] needs to
 2014   /// be recomputed during the next [PipelineOwner.flushCompositingBits] engine
 2015   /// phase.
 2016   ///
 2017   /// When the subtree is mutated, we need to recompute our
 2018   /// [needsCompositing] bit, and some of our ancestors need to do the
 2019   /// same (in case ours changed in a way that will change theirs). To
 2020   /// this end, [adoptChild] and [dropChild] call this method, and, as
 2021   /// necessary, this method calls the parent's, etc, walking up the
 2022   /// tree to mark all the nodes that need updating.
 2023   ///
 2024   /// This method does not schedule a rendering frame, because since
 2025   /// it cannot be the case that _only_ the compositing bits changed,
 2026   /// something else will have scheduled a frame for us.
 2027   void markNeedsCompositingBitsUpdate() {
 2028     if (_needsCompositingBitsUpdate)
 2029       return;
 2030     _needsCompositingBitsUpdate = true;
 2031     if (parent is RenderObject) {
 2032       final RenderObject parent = this.parent as RenderObject;
 2033       if (parent._needsCompositingBitsUpdate)
 2034         return;
 2035       if (!isRepaintBoundary && !parent.isRepaintBoundary) {
 2036         parent.markNeedsCompositingBitsUpdate();
 2037         return;
 2038       }
 2039     }
 2040     assert(() {
 2041       final AbstractNode? parent = this.parent;
 2042       if (parent is RenderObject)
 2043         return parent._needsCompositing;
 2044       return true;
 2045     }());
 2046     // parent is fine (or there isn't one), but we are dirty
 2047     if (owner != null)
 2048       owner!._nodesNeedingCompositingBitsUpdate.add(this);
 2049   }
 2050 
 2051   late bool _needsCompositing; // initialized in the constructor
 2052   /// Whether we or one of our descendants has a compositing layer.
 2053   ///
 2054   /// If this node needs compositing as indicated by this bit, then all ancestor
 2055   /// nodes will also need compositing.
 2056   ///
 2057   /// Only legal to call after [PipelineOwner.flushLayout] and
 2058   /// [PipelineOwner.flushCompositingBits] have been called.
 2059   bool get needsCompositing {
 2060     assert(!_needsCompositingBitsUpdate); // make sure we don't use this bit when it is dirty
 2061     return _needsCompositing;
 2062   }
 2063 
 2064   void _updateCompositingBits() {
 2065     if (!_needsCompositingBitsUpdate)
 2066       return;
 2067     final bool oldNeedsCompositing = _needsCompositing;
 2068     _needsCompositing = false;
 2069     visitChildren((RenderObject child) {
 2070       child._updateCompositingBits();
 2071       if (child.needsCompositing)
 2072         _needsCompositing = true;
 2073     });
 2074     if (isRepaintBoundary || alwaysNeedsCompositing)
 2075       _needsCompositing = true;
 2076     if (oldNeedsCompositing != _needsCompositing)
 2077       markNeedsPaint();
 2078     _needsCompositingBitsUpdate = false;
 2079   }
 2080 
 2081   /// Whether this render object's paint information is dirty.
 2082   ///
 2083   /// This is only set in debug mode. In general, render objects should not need
 2084   /// to condition their runtime behavior on whether they are dirty or not,
 2085   /// since they should only be marked dirty immediately prior to being laid
 2086   /// out and painted. (In release builds, this throws.)
 2087   ///
 2088   /// It is intended to be used by tests and asserts.
 2089   ///
 2090   /// It is possible (and indeed, quite common) for [debugNeedsPaint] to be
 2091   /// false and [debugNeedsLayout] to be true. The render object will still be
 2092   /// repainted in the next frame when this is the case, because the
 2093   /// [markNeedsPaint] method is implicitly called by the framework after a
 2094   /// render object is laid out, prior to the paint phase.
 2095   bool get debugNeedsPaint {
 2096     late bool result;
 2097     assert(() {
 2098       result = _needsPaint;
 2099       return true;
 2100     }());
 2101     return result;
 2102   }
 2103   bool _needsPaint = true;
 2104 
 2105   /// Mark this render object as having changed its visual appearance.
 2106   ///
 2107   /// Rather than eagerly updating this render object's display list
 2108   /// in response to writes, we instead mark the render object as needing to
 2109   /// paint, which schedules a visual update. As part of the visual update, the
 2110   /// rendering pipeline will give this render object an opportunity to update
 2111   /// its display list.
 2112   ///
 2113   /// This mechanism batches the painting work so that multiple sequential
 2114   /// writes are coalesced, removing redundant computation.
 2115   ///
 2116   /// Once [markNeedsPaint] has been called on a render object,
 2117   /// [debugNeedsPaint] returns true for that render object until just after
 2118   /// the pipeline owner has called [paint] on the render object.
 2119   ///
 2120   /// See also:
 2121   ///
 2122   ///  * [RepaintBoundary], to scope a subtree of render objects to their own
 2123   ///    layer, thus limiting the number of nodes that [markNeedsPaint] must mark
 2124   ///    dirty.
 2125   void markNeedsPaint() {
 2126     assert(owner == null || !owner!.debugDoingPaint);
 2127     if (_needsPaint)
 2128       return;
 2129     _needsPaint = true;
 2130     if (isRepaintBoundary) {
 2131       assert(() {
 2132         if (debugPrintMarkNeedsPaintStacks)
 2133           debugPrintStack(label: 'markNeedsPaint() called for $this');
 2134         return true;
 2135       }());
 2136       // If we always have our own layer, then we can just repaint
 2137       // ourselves without involving any other nodes.
 2138       assert(_layer is OffsetLayer);
 2139       if (owner != null) {
 2140         owner!._nodesNeedingPaint.add(this);
 2141         owner!.requestVisualUpdate();
 2142       }
 2143     } else if (parent is RenderObject) {
 2144       final RenderObject parent = this.parent as RenderObject;
 2145       parent.markNeedsPaint();
 2146       assert(parent == this.parent);
 2147     } else {
 2148       assert(() {
 2149         if (debugPrintMarkNeedsPaintStacks)
 2150           debugPrintStack(label: 'markNeedsPaint() called for $this (root of render tree)');
 2151         return true;
 2152       }());
 2153       // If we're the root of the render tree (probably a RenderView),
 2154       // then we have to paint ourselves, since nobody else can paint
 2155       // us. We don't add ourselves to _nodesNeedingPaint in this
 2156       // case, because the root is always told to paint regardless.
 2157       if (owner != null)
 2158         owner!.requestVisualUpdate();
 2159     }
 2160   }
 2161 
 2162   // Called when flushPaint() tries to make us paint but our layer is detached.
 2163   // To make sure that our subtree is repainted when it's finally reattached,
 2164   // even in the case where some ancestor layer is itself never marked dirty, we
 2165   // have to mark our entire detached subtree as dirty and needing to be
 2166   // repainted. That way, we'll eventually be repainted.
 2167   void _skippedPaintingOnLayer() {
 2168     assert(attached);
 2169     assert(isRepaintBoundary);
 2170     assert(_needsPaint);
 2171     assert(_layer != null);
 2172     assert(!_layer!.attached);
 2173     AbstractNode? node = parent;
 2174     while (node is RenderObject) {
 2175       if (node.isRepaintBoundary) {
 2176         if (node._layer == null)
 2177           break; // looks like the subtree here has never been painted. let it handle itself.
 2178         if (node._layer!.attached)
 2179           break; // it's the one that detached us, so it's the one that will decide to repaint us.
 2180         node._needsPaint = true;
 2181       }
 2182       node = node.parent;
 2183     }
 2184   }
 2185 
 2186   /// Bootstrap the rendering pipeline by scheduling the very first paint.
 2187   ///
 2188   /// Requires that this render object is attached, is the root of the render
 2189   /// tree, and has a composited layer.
 2190   ///
 2191   /// See [RenderView] for an example of how this function is used.
 2192   void scheduleInitialPaint(ContainerLayer rootLayer) {
 2193     assert(rootLayer.attached);
 2194     assert(attached);
 2195     assert(parent is! RenderObject);
 2196     assert(!owner!._debugDoingPaint);
 2197     assert(isRepaintBoundary);
 2198     assert(_layer == null);
 2199     _layer = rootLayer;
 2200     assert(_needsPaint);
 2201     owner!._nodesNeedingPaint.add(this);
 2202   }
 2203 
 2204   /// Replace the layer. This is only valid for the root of a render
 2205   /// object subtree (whatever object [scheduleInitialPaint] was
 2206   /// called on).
 2207   ///
 2208   /// This might be called if, e.g., the device pixel ratio changed.
 2209   void replaceRootLayer(OffsetLayer rootLayer) {
 2210     assert(rootLayer.attached);
 2211     assert(attached);
 2212     assert(parent is! RenderObject);
 2213     assert(!owner!._debugDoingPaint);
 2214     assert(isRepaintBoundary);
 2215     assert(_layer != null); // use scheduleInitialPaint the first time
 2216     _layer!.detach();
 2217     _layer = rootLayer;
 2218     markNeedsPaint();
 2219   }
 2220 
 2221   void _paintWithContext(PaintingContext context, Offset offset) {
 2222     assert(() {
 2223       if (_debugDoingThisPaint) {
 2224         throw FlutterError.fromParts(<DiagnosticsNode>[
 2225           ErrorSummary('Tried to paint a RenderObject reentrantly.'),
 2226           describeForError(
 2227             'The following RenderObject was already being painted when it was '
 2228             'painted again'
 2229           ),
 2230           ErrorDescription(
 2231             'Since this typically indicates an infinite recursion, it is '
 2232             'disallowed.'
 2233           ),
 2234         ]);
 2235       }
 2236       return true;
 2237     }());
 2238     // If we still need layout, then that means that we were skipped in the
 2239     // layout phase and therefore don't need painting. We might not know that
 2240     // yet (that is, our layer might not have been detached yet), because the
 2241     // same node that skipped us in layout is above us in the tree (obviously)
 2242     // and therefore may not have had a chance to paint yet (since the tree
 2243     // paints in reverse order). In particular this will happen if they have
 2244     // a different layer, because there's a repaint boundary between us.
 2245     if (_needsLayout)
 2246       return;
 2247     assert(() {
 2248       if (_needsCompositingBitsUpdate) {
 2249         if (parent is RenderObject) {
 2250           final RenderObject parent = this.parent as RenderObject;
 2251           bool visitedByParent = false;
 2252           parent.visitChildren((RenderObject child) {
 2253             if (child == this) {
 2254               visitedByParent = true;
 2255             }
 2256           });
 2257           if (!visitedByParent) {
 2258             throw FlutterError.fromParts(<DiagnosticsNode>[
 2259               ErrorSummary(
 2260                 "A RenderObject was not visited by the parent's visitChildren "
 2261                 'during paint.',
 2262               ),
 2263               parent.describeForError(
 2264                 'The parent was',
 2265               ),
 2266               describeForError(
 2267                 'The child that was not visited was'
 2268               ),
 2269               ErrorDescription(
 2270                 'A RenderObject with children must implement visitChildren and '
 2271                 'call the visitor exactly once for each child; it also should not '
 2272                 'paint children that were removed with dropChild.'
 2273               ),
 2274               ErrorHint(
 2275                 'This usually indicates an error in the Flutter framework itself.'
 2276               ),
 2277             ]);
 2278           }
 2279         }
 2280         throw FlutterError.fromParts(<DiagnosticsNode>[
 2281           ErrorSummary(
 2282             'Tried to paint a RenderObject before its compositing bits were '
 2283             'updated.'
 2284           ),
 2285           describeForError(
 2286             'The following RenderObject was marked as having dirty compositing '
 2287             'bits at the time that it was painted',
 2288           ),
 2289           ErrorDescription(
 2290             'A RenderObject that still has dirty compositing bits cannot be '
 2291             'painted because this indicates that the tree has not yet been '
 2292             'properly configured for creating the layer tree.'
 2293           ),
 2294           ErrorHint(
 2295             'This usually indicates an error in the Flutter framework itself.'
 2296           ),
 2297         ]);
 2298       }
 2299       return true;
 2300     }());
 2301     RenderObject? debugLastActivePaint;
 2302     assert(() {
 2303       _debugDoingThisPaint = true;
 2304       debugLastActivePaint = _debugActivePaint;
 2305       _debugActivePaint = this;
 2306       assert(!isRepaintBoundary || _layer != null);
 2307       return true;
 2308     }());
 2309     _needsPaint = false;
 2310     try {
 2311       paint(context, offset);
 2312       assert(!_needsLayout); // check that the paint() method didn't mark us dirty again
 2313       assert(!_needsPaint); // check that the paint() method didn't mark us dirty again
 2314     } catch (e, stack) {
 2315       _debugReportException('paint', e, stack);
 2316     }
 2317     assert(() {
 2318       debugPaint(context, offset);
 2319       _debugActivePaint = debugLastActivePaint;
 2320       _debugDoingThisPaint = false;
 2321       return true;
 2322     }());
 2323   }
 2324 
 2325   /// An estimate of the bounds within which this render object will paint.
 2326   /// Useful for debugging flags such as [debugPaintLayerBordersEnabled].
 2327   ///
 2328   /// These are also the bounds used by [showOnScreen] to make a [RenderObject]
 2329   /// visible on screen.
 2330   Rect get paintBounds;
 2331 
 2332   /// Override this method to paint debugging information.
 2333   void debugPaint(PaintingContext context, Offset offset) { }
 2334 
 2335   /// Paint this render object into the given context at the given offset.
 2336   ///
 2337   /// Subclasses should override this method to provide a visual appearance
 2338   /// for themselves. The render object's local coordinate system is
 2339   /// axis-aligned with the coordinate system of the context's canvas and the
 2340   /// render object's local origin (i.e, x=0 and y=0) is placed at the given
 2341   /// offset in the context's canvas.
 2342   ///
 2343   /// Do not call this function directly. If you wish to paint yourself, call
 2344   /// [markNeedsPaint] instead to schedule a call to this function. If you wish
 2345   /// to paint one of your children, call [PaintingContext.paintChild] on the
 2346   /// given `context`.
 2347   ///
 2348   /// When painting one of your children (via a paint child function on the
 2349   /// given context), the current canvas held by the context might change
 2350   /// because draw operations before and after painting children might need to
 2351   /// be recorded on separate compositing layers.
 2352   void paint(PaintingContext context, Offset offset) { }
 2353 
 2354   /// Applies the transform that would be applied when painting the given child
 2355   /// to the given matrix.
 2356   ///
 2357   /// Used by coordinate conversion functions to translate coordinates local to
 2358   /// one render object into coordinates local to another render object.
 2359   void applyPaintTransform(covariant RenderObject child, Matrix4 transform) {
 2360     assert(child.parent == this);
 2361   }
 2362 
 2363   /// Applies the paint transform up the tree to `ancestor`.
 2364   ///
 2365   /// Returns a matrix that maps the local paint coordinate system to the
 2366   /// coordinate system of `ancestor`.
 2367   ///
 2368   /// If `ancestor` is null, this method returns a matrix that maps from the
 2369   /// local paint coordinate system to the coordinate system of the
 2370   /// [PipelineOwner.rootNode]. For the render tree owner by the
 2371   /// [RendererBinding] (i.e. for the main render tree displayed on the device)
 2372   /// this means that this method maps to the global coordinate system in
 2373   /// logical pixels. To get physical pixels, use [applyPaintTransform] from the
 2374   /// [RenderView] to further transform the coordinate.
 2375   Matrix4 getTransformTo(RenderObject? ancestor) {
 2376     final bool ancestorSpecified = ancestor != null;
 2377     assert(attached);
 2378     if (ancestor == null) {
 2379       final AbstractNode? rootNode = owner!.rootNode;
 2380       if (rootNode is RenderObject)
 2381         ancestor = rootNode;
 2382     }
 2383     final List<RenderObject> renderers = <RenderObject>[];
 2384     for (RenderObject renderer = this; renderer != ancestor; renderer = renderer.parent as RenderObject) {
 2385       assert(renderer != null); // Failed to find ancestor in parent chain.
 2386       renderers.add(renderer);
 2387     }
 2388     if (ancestorSpecified)
 2389       renderers.add(ancestor!);
 2390     final Matrix4 transform = Matrix4.identity();
 2391     for (int index = renderers.length - 1; index > 0; index -= 1) {
 2392       renderers[index].applyPaintTransform(renderers[index - 1], transform);
 2393     }
 2394     return transform;
 2395   }
 2396 
 2397 
 2398   /// Returns a rect in this object's coordinate system that describes
 2399   /// the approximate bounding box of the clip rect that would be
 2400   /// applied to the given child during the paint phase, if any.
 2401   ///
 2402   /// Returns null if the child would not be clipped.
 2403   ///
 2404   /// This is used in the semantics phase to avoid including children
 2405   /// that are not physically visible.
 2406   Rect? describeApproximatePaintClip(covariant RenderObject child) => null;
 2407 
 2408   /// Returns a rect in this object's coordinate system that describes
 2409   /// which [SemanticsNode]s produced by the `child` should be included in the
 2410   /// semantics tree. [SemanticsNode]s from the `child` that are positioned
 2411   /// outside of this rect will be dropped. Child [SemanticsNode]s that are
 2412   /// positioned inside this rect, but outside of [describeApproximatePaintClip]
 2413   /// will be included in the tree marked as hidden. Child [SemanticsNode]s
 2414   /// that are inside of both rect will be included in the tree as regular
 2415   /// nodes.
 2416   ///
 2417   /// This method only returns a non-null value if the semantics clip rect
 2418   /// is different from the rect returned by [describeApproximatePaintClip].
 2419   /// If the semantics clip rect and the paint clip rect are the same, this
 2420   /// method returns null.
 2421   ///
 2422   /// A viewport would typically implement this method to include semantic nodes
 2423   /// in the semantics tree that are currently hidden just before the leading
 2424   /// or just after the trailing edge. These nodes have to be included in the
 2425   /// semantics tree to implement implicit accessibility scrolling on iOS where
 2426   /// the viewport scrolls implicitly when moving the accessibility focus from
 2427   /// a the last visible node in the viewport to the first hidden one.
 2428   ///
 2429   /// See also:
 2430   ///
 2431   /// * [RenderViewportBase.cacheExtent], used by viewports to extend their
 2432   ///   semantics clip beyond their approximate paint clip.
 2433   Rect? describeSemanticsClip(covariant RenderObject? child) => null;
 2434 
 2435   // SEMANTICS
 2436 
 2437   /// Bootstrap the semantics reporting mechanism by marking this node
 2438   /// as needing a semantics update.
 2439   ///
 2440   /// Requires that this render object is attached, and is the root of
 2441   /// the render tree.
 2442   ///
 2443   /// See [RendererBinding] for an example of how this function is used.
 2444   void scheduleInitialSemantics() {
 2445     assert(attached);
 2446     assert(parent is! RenderObject);
 2447     assert(!owner!._debugDoingSemantics);
 2448     assert(_semantics == null);
 2449     assert(_needsSemanticsUpdate);
 2450     assert(owner!._semanticsOwner != null);
 2451     owner!._nodesNeedingSemantics.add(this);
 2452     owner!.requestVisualUpdate();
 2453   }
 2454 
 2455   /// Report the semantics of this node, for example for accessibility purposes.
 2456   ///
 2457   /// This method should be overridden by subclasses that have interesting
 2458   /// semantic information.
 2459   ///
 2460   /// The given [SemanticsConfiguration] object is mutable and should be
 2461   /// annotated in a manner that describes the current state. No reference
 2462   /// should be kept to that object; mutating it outside of the context of the
 2463   /// [describeSemanticsConfiguration] call (for example as a result of
 2464   /// asynchronous computation) will at best have no useful effect and at worse
 2465   /// will cause crashes as the data will be in an inconsistent state.
 2466   ///
 2467   /// {@tool snippet}
 2468   ///
 2469   /// The following snippet will describe the node as a button that responds to
 2470   /// tap actions.
 2471   ///
 2472   /// ```dart
 2473   /// abstract class SemanticButtonRenderObject extends RenderObject {
 2474   ///   @override
 2475   ///   void describeSemanticsConfiguration(SemanticsConfiguration config) {
 2476   ///     super.describeSemanticsConfiguration(config);
 2477   ///     config
 2478   ///       ..onTap = _handleTap
 2479   ///       ..label = 'I am a button'
 2480   ///       ..isButton = true;
 2481   ///   }
 2482   ///
 2483   ///   void _handleTap() {
 2484   ///     // Do something.
 2485   ///   }
 2486   /// }
 2487   /// ```
 2488   /// {@end-tool}
 2489   @protected
 2490   void describeSemanticsConfiguration(SemanticsConfiguration config) {
 2491     // Nothing to do by default.
 2492   }
 2493 
 2494   /// Sends a [SemanticsEvent] associated with this render object's [SemanticsNode].
 2495   ///
 2496   /// If this render object has no semantics information, the first parent
 2497   /// render object with a non-null semantic node is used.
 2498   ///
 2499   /// If semantics are disabled, no events are dispatched.
 2500   ///
 2501   /// See [SemanticsNode.sendEvent] for a full description of the behavior.
 2502   void sendSemanticsEvent(SemanticsEvent semanticsEvent) {
 2503     if (owner!.semanticsOwner == null)
 2504       return;
 2505     if (_semantics != null && !_semantics!.isMergedIntoParent) {
 2506       _semantics!.sendEvent(semanticsEvent);
 2507     } else if (parent != null) {
 2508       final RenderObject renderParent = parent as RenderObject;
 2509       renderParent.sendSemanticsEvent(semanticsEvent);
 2510     }
 2511   }
 2512 
 2513   // Use [_semanticsConfiguration] to access.
 2514   SemanticsConfiguration? _cachedSemanticsConfiguration;
 2515 
 2516   SemanticsConfiguration get _semanticsConfiguration {
 2517     if (_cachedSemanticsConfiguration == null) {
 2518       _cachedSemanticsConfiguration = SemanticsConfiguration();
 2519       describeSemanticsConfiguration(_cachedSemanticsConfiguration!);
 2520     }
 2521     return _cachedSemanticsConfiguration!;
 2522   }
 2523 
 2524   /// The bounding box, in the local coordinate system, of this
 2525   /// object, for accessibility purposes.
 2526   Rect get semanticBounds;
 2527 
 2528   bool _needsSemanticsUpdate = true;
 2529   SemanticsNode? _semantics;
 2530 
 2531   /// The semantics of this render object.
 2532   ///
 2533   /// Exposed only for testing and debugging. To learn about the semantics of
 2534   /// render objects in production, obtain a [SemanticsHandle] from
 2535   /// [PipelineOwner.ensureSemantics].
 2536   ///
 2537   /// Only valid in debug and profile mode. In release builds, always returns
 2538   /// null.
 2539   SemanticsNode? get debugSemantics {
 2540     if (!kReleaseMode) {
 2541       return _semantics;
 2542     }
 2543     return null;
 2544   }
 2545 
 2546   /// Removes all semantics from this render object and its descendants.
 2547   ///
 2548   /// Should only be called on objects whose [parent] is not a [RenderObject].
 2549   ///
 2550   /// Override this method if you instantiate new [SemanticsNode]s in an
 2551   /// overridden [assembleSemanticsNode] method, to dispose of those nodes.
 2552   @mustCallSuper
 2553   void clearSemantics() {
 2554     _needsSemanticsUpdate = true;
 2555     _semantics = null;
 2556     visitChildren((RenderObject child) {
 2557       child.clearSemantics();
 2558     });
 2559   }
 2560 
 2561   /// Mark this node as needing an update to its semantics description.
 2562   ///
 2563   /// This must be called whenever the semantics configuration of this
 2564   /// [RenderObject] as annotated by [describeSemanticsConfiguration] changes in
 2565   /// any way to update the semantics tree.
 2566   void markNeedsSemanticsUpdate() {
 2567     assert(!attached || !owner!._debugDoingSemantics);
 2568     if (!attached || owner!._semanticsOwner == null) {
 2569       _cachedSemanticsConfiguration = null;
 2570       return;
 2571     }
 2572 
 2573     // Dirty the semantics tree starting at `this` until we have reached a
 2574     // RenderObject that is a semantics boundary. All semantics past this
 2575     // RenderObject are still up-to date. Therefore, we will later only rebuild
 2576     // the semantics subtree starting at the identified semantics boundary.
 2577 
 2578     final bool wasSemanticsBoundary = _semantics != null && _cachedSemanticsConfiguration?.isSemanticBoundary == true;
 2579     _cachedSemanticsConfiguration = null;
 2580     bool isEffectiveSemanticsBoundary = _semanticsConfiguration.isSemanticBoundary && wasSemanticsBoundary;
 2581     RenderObject node = this;
 2582 
 2583     while (!isEffectiveSemanticsBoundary && node.parent is RenderObject) {
 2584       if (node != this && node._needsSemanticsUpdate)
 2585         break;
 2586       node._needsSemanticsUpdate = true;
 2587 
 2588       node = node.parent as RenderObject;
 2589       isEffectiveSemanticsBoundary = node._semanticsConfiguration.isSemanticBoundary;
 2590       if (isEffectiveSemanticsBoundary && node._semantics == null) {
 2591         // We have reached a semantics boundary that doesn't own a semantics node.
 2592         // That means the semantics of this branch are currently blocked and will
 2593         // not appear in the semantics tree. We can abort the walk here.
 2594         return;
 2595       }
 2596     }
 2597     if (node != this && _semantics != null && _needsSemanticsUpdate) {
 2598       // If `this` node has already been added to [owner._nodesNeedingSemantics]
 2599       // remove it as it is no longer guaranteed that its semantics
 2600       // node will continue to be in the tree. If it still is in the tree, the
 2601       // ancestor `node` added to [owner._nodesNeedingSemantics] at the end of
 2602       // this block will ensure that the semantics of `this` node actually gets
 2603       // updated.
 2604       // (See semantics_10_test.dart for an example why this is required).
 2605       owner!._nodesNeedingSemantics.remove(this);
 2606     }
 2607     if (!node._needsSemanticsUpdate) {
 2608       node._needsSemanticsUpdate = true;
 2609       if (owner != null) {
 2610         assert(node._semanticsConfiguration.isSemanticBoundary || node.parent is! RenderObject);
 2611         owner!._nodesNeedingSemantics.add(node);
 2612         owner!.requestVisualUpdate();
 2613       }
 2614     }
 2615   }
 2616 
 2617   /// Updates the semantic information of the render object.
 2618   void _updateSemantics() {
 2619     assert(_semanticsConfiguration.isSemanticBoundary || parent is! RenderObject);
 2620     if (_needsLayout) {
 2621       // There's not enough information in this subtree to compute semantics.
 2622       // The subtree is probably being kept alive by a viewport but not laid out.
 2623       return;
 2624     }
 2625     final _SemanticsFragment fragment = _getSemanticsForParent(
 2626       mergeIntoParent: _semantics?.parent?.isPartOfNodeMerging ?? false,
 2627     );
 2628     assert(fragment is _InterestingSemanticsFragment);
 2629     final _InterestingSemanticsFragment interestingFragment = fragment as _InterestingSemanticsFragment;
 2630     final List<SemanticsNode> result = <SemanticsNode>[];
 2631     interestingFragment.compileChildren(
 2632       parentSemanticsClipRect: _semantics?.parentSemanticsClipRect,
 2633       parentPaintClipRect: _semantics?.parentPaintClipRect,
 2634       elevationAdjustment: _semantics?.elevationAdjustment ?? 0.0,
 2635       result: result,
 2636     );
 2637     final SemanticsNode node = result.single;
 2638     // Fragment only wants to add this node's SemanticsNode to the parent.
 2639     assert(interestingFragment.config == null && node == _semantics);
 2640   }
 2641 
 2642   /// Returns the semantics that this node would like to add to its parent.
 2643   _SemanticsFragment _getSemanticsForParent({
 2644     required bool mergeIntoParent,
 2645   }) {
 2646     assert(mergeIntoParent != null);
 2647     assert(!_needsLayout, 'Updated layout information required for $this to calculate semantics.');
 2648 
 2649     final SemanticsConfiguration config = _semanticsConfiguration;
 2650     bool dropSemanticsOfPreviousSiblings = config.isBlockingSemanticsOfPreviouslyPaintedNodes;
 2651 
 2652     final bool producesForkingFragment = !config.hasBeenAnnotated && !config.isSemanticBoundary;
 2653     final List<_InterestingSemanticsFragment> fragments = <_InterestingSemanticsFragment>[];
 2654     final Set<_InterestingSemanticsFragment> toBeMarkedExplicit = <_InterestingSemanticsFragment>{};
 2655     final bool childrenMergeIntoParent = mergeIntoParent || config.isMergingSemanticsOfDescendants;
 2656 
 2657     // When set to true there's currently not enough information in this subtree
 2658     // to compute semantics. In this case the walk needs to be aborted and no
 2659     // SemanticsNodes in the subtree should be updated.
 2660     // This will be true for subtrees that are currently kept alive by a
 2661     // viewport but not laid out.
 2662     bool abortWalk = false;
 2663 
 2664     visitChildrenForSemantics((RenderObject renderChild) {
 2665       if (abortWalk || _needsLayout) {
 2666         abortWalk = true;
 2667         return;
 2668       }
 2669       final _SemanticsFragment parentFragment = renderChild._getSemanticsForParent(
 2670         mergeIntoParent: childrenMergeIntoParent,
 2671       );
 2672       if (parentFragment.abortsWalk) {
 2673         abortWalk = true;
 2674         return;
 2675       }
 2676       if (parentFragment.dropsSemanticsOfPreviousSiblings) {
 2677         fragments.clear();
 2678         toBeMarkedExplicit.clear();
 2679         if (!config.isSemanticBoundary)
 2680           dropSemanticsOfPreviousSiblings = true;
 2681       }
 2682       // Figure out which child fragments are to be made explicit.
 2683       for (final _InterestingSemanticsFragment fragment in parentFragment.interestingFragments) {
 2684         fragments.add(fragment);
 2685         fragment.addAncestor(this);
 2686         fragment.addTags(config.tagsForChildren);
 2687         if (config.explicitChildNodes || parent is! RenderObject) {
 2688           fragment.markAsExplicit();
 2689           continue;
 2690         }
 2691         if (!fragment.hasConfigForParent || producesForkingFragment)
 2692           continue;
 2693         if (!config.isCompatibleWith(fragment.config))
 2694           toBeMarkedExplicit.add(fragment);
 2695         final int siblingLength = fragments.length - 1;
 2696         for (int i = 0; i < siblingLength; i += 1) {
 2697           final _InterestingSemanticsFragment siblingFragment = fragments[i];
 2698           if (!fragment.config!.isCompatibleWith(siblingFragment.config)) {
 2699             toBeMarkedExplicit.add(fragment);
 2700             toBeMarkedExplicit.add(siblingFragment);
 2701           }
 2702         }
 2703       }
 2704     });
 2705 
 2706     if (abortWalk) {
 2707       return _AbortingSemanticsFragment(owner: this);
 2708     }
 2709 
 2710     for (final _InterestingSemanticsFragment fragment in toBeMarkedExplicit)
 2711       fragment.markAsExplicit();
 2712 
 2713     _needsSemanticsUpdate = false;
 2714 
 2715     _SemanticsFragment result;
 2716     if (parent is! RenderObject) {
 2717       assert(!config.hasBeenAnnotated);
 2718       assert(!mergeIntoParent);
 2719       result = _RootSemanticsFragment(
 2720         owner: this,
 2721         dropsSemanticsOfPreviousSiblings: dropSemanticsOfPreviousSiblings,
 2722       );
 2723     } else if (producesForkingFragment) {
 2724       result = _ContainerSemanticsFragment(
 2725         dropsSemanticsOfPreviousSiblings: dropSemanticsOfPreviousSiblings,
 2726       );
 2727     } else {
 2728       result = _SwitchableSemanticsFragment(
 2729         config: config,
 2730         mergeIntoParent: mergeIntoParent,
 2731         owner: this,
 2732         dropsSemanticsOfPreviousSiblings: dropSemanticsOfPreviousSiblings,
 2733       );
 2734       if (config.isSemanticBoundary) {
 2735         final _SwitchableSemanticsFragment fragment = result as _SwitchableSemanticsFragment;
 2736         fragment.markAsExplicit();
 2737       }
 2738     }
 2739 
 2740     result.addAll(fragments);
 2741 
 2742     return result;
 2743   }
 2744 
 2745   /// Called when collecting the semantics of this node.
 2746   ///
 2747   /// The implementation has to return the children in paint order skipping all
 2748   /// children that are not semantically relevant (e.g. because they are
 2749   /// invisible).
 2750   ///
 2751   /// The default implementation mirrors the behavior of
 2752   /// [visitChildren] (which is supposed to walk all the children).
 2753   void visitChildrenForSemantics(RenderObjectVisitor visitor) {
 2754     visitChildren(visitor);
 2755   }
 2756 
 2757   /// Assemble the [SemanticsNode] for this [RenderObject].
 2758   ///
 2759   /// If [describeSemanticsConfiguration] sets
 2760   /// [SemanticsConfiguration.isSemanticBoundary] to true, this method is called
 2761   /// with the `node` created for this [RenderObject], the `config` to be
 2762   /// applied to that node and the `children` [SemanticsNode]s that descendants
 2763   /// of this RenderObject have generated.
 2764   ///
 2765   /// By default, the method will annotate `node` with `config` and add the
 2766   /// `children` to it.
 2767   ///
 2768   /// Subclasses can override this method to add additional [SemanticsNode]s
 2769   /// to the tree. If new [SemanticsNode]s are instantiated in this method
 2770   /// they must be disposed in [clearSemantics].
 2771   void assembleSemanticsNode(
 2772     SemanticsNode node,
 2773     SemanticsConfiguration config,
 2774     Iterable<SemanticsNode> children,
 2775   ) {
 2776     assert(node == _semantics);
 2777     // TODO(a14n): remove the following cast by updating type of parameter in either updateWith or assembleSemanticsNode
 2778     node.updateWith(config: config, childrenInInversePaintOrder: children as List<SemanticsNode>);
 2779   }
 2780 
 2781   // EVENTS
 2782 
 2783   /// Override this method to handle pointer events that hit this render object.
 2784   @override
 2785   void handleEvent(PointerEvent event, covariant HitTestEntry entry) { }
 2786 
 2787 
 2788   // HIT TESTING
 2789 
 2790   // RenderObject subclasses are expected to have a method like the following
 2791   // (with the signature being whatever passes for coordinates for this
 2792   // particular class):
 2793   //
 2794   // bool hitTest(HitTestResult result, { Offset position }) {
 2795   //   // If the given position is not inside this node, then return false.
 2796   //   // Otherwise:
 2797   //   // For each child that intersects the position, in z-order starting from
 2798   //   // the top, call hitTest() for that child, passing it /result/, and the
 2799   //   // coordinates converted to the child's coordinate origin, and stop at
 2800   //   // the first child that returns true.
 2801   //   // Then, add yourself to /result/, and return true.
 2802   // }
 2803   //
 2804   // If you add yourself to /result/ and still return false, then that means you
 2805   // will see events but so will objects below you.
 2806 
 2807 
 2808   /// Returns a human understandable name.
 2809   @override
 2810   String toStringShort() {
 2811     String header = describeIdentity(this);
 2812     if (_relayoutBoundary != null && _relayoutBoundary != this) {
 2813       int count = 1;
 2814       RenderObject? target = parent as RenderObject?;
 2815       while (target != null && target != _relayoutBoundary) {
 2816         target = target.parent as RenderObject?;
 2817         count += 1;
 2818       }
 2819       header += ' relayoutBoundary=up$count';
 2820     }
 2821     if (_needsLayout)
 2822       header += ' NEEDS-LAYOUT';
 2823     if (_needsPaint)
 2824       header += ' NEEDS-PAINT';
 2825     if (_needsCompositingBitsUpdate)
 2826       header += ' NEEDS-COMPOSITING-BITS-UPDATE';
 2827     if (!attached)
 2828       header += ' DETACHED';
 2829     return header;
 2830   }
 2831 
 2832   @override
 2833   String toString({ DiagnosticLevel minLevel = DiagnosticLevel.info }) => toStringShort();
 2834 
 2835   /// Returns a description of the tree rooted at this node.
 2836   /// If the prefix argument is provided, then every line in the output
 2837   /// will be prefixed by that string.
 2838   @override
 2839   String toStringDeep({
 2840     String prefixLineOne = '',
 2841     String? prefixOtherLines = '',
 2842     DiagnosticLevel minLevel = DiagnosticLevel.debug,
 2843   }) {
 2844     RenderObject? debugPreviousActiveLayout;
 2845     assert(() {
 2846       debugPreviousActiveLayout = _debugActiveLayout;
 2847       _debugActiveLayout = null;
 2848       return true;
 2849     }());
 2850     final String result = super.toStringDeep(
 2851       prefixLineOne: prefixLineOne,
 2852       prefixOtherLines: prefixOtherLines,
 2853       minLevel: minLevel,
 2854     );
 2855     assert(() {
 2856       _debugActiveLayout = debugPreviousActiveLayout;
 2857       return true;
 2858     }());
 2859     return result;
 2860   }
 2861 
 2862   /// Returns a one-line detailed description of the render object.
 2863   /// This description is often somewhat long.
 2864   ///
 2865   /// This includes the same information for this RenderObject as given by
 2866   /// [toStringDeep], but does not recurse to any children.
 2867   @override
 2868   String toStringShallow({
 2869     String joiner = ', ',
 2870     DiagnosticLevel minLevel = DiagnosticLevel.debug,
 2871   }) {
 2872     RenderObject? debugPreviousActiveLayout;
 2873     assert(() {
 2874       debugPreviousActiveLayout = _debugActiveLayout;
 2875       _debugActiveLayout = null;
 2876       return true;
 2877     }());
 2878     final String result = super.toStringShallow(joiner: joiner, minLevel: minLevel);
 2879     assert(() {
 2880       _debugActiveLayout = debugPreviousActiveLayout;
 2881       return true;
 2882     }());
 2883     return result;
 2884   }
 2885 
 2886   @protected
 2887   @override
 2888   void debugFillProperties(DiagnosticPropertiesBuilder properties) {
 2889     super.debugFillProperties(properties);
 2890     properties.add(FlagProperty('needsCompositing', value: _needsCompositing, ifTrue: 'needs compositing'));
 2891     properties.add(DiagnosticsProperty<Object?>('creator', debugCreator, defaultValue: null, level: DiagnosticLevel.debug));
 2892     properties.add(DiagnosticsProperty<ParentData>('parentData', parentData, tooltip: _debugCanParentUseSize == true ? 'can use size' : null, missingIfNull: true));
 2893     properties.add(DiagnosticsProperty<Constraints>('constraints', _constraints, missingIfNull: true));
 2894     // don't access it via the "layer" getter since that's only valid when we don't need paint
 2895     properties.add(DiagnosticsProperty<ContainerLayer>('layer', _layer, defaultValue: null));
 2896     properties.add(DiagnosticsProperty<SemanticsNode>('semantics node', _semantics, defaultValue: null));
 2897     properties.add(FlagProperty(
 2898       'isBlockingSemanticsOfPreviouslyPaintedNodes',
 2899       value: _semanticsConfiguration.isBlockingSemanticsOfPreviouslyPaintedNodes,
 2900       ifTrue: 'blocks semantics of earlier render objects below the common boundary',
 2901     ));
 2902     properties.add(FlagProperty('isSemanticBoundary', value: _semanticsConfiguration.isSemanticBoundary, ifTrue: 'semantic boundary'));
 2903   }
 2904 
 2905   @override
 2906   List<DiagnosticsNode> debugDescribeChildren() => <DiagnosticsNode>[];
 2907 
 2908   /// Attempt to make (a portion of) this or a descendant [RenderObject] visible
 2909   /// on screen.
 2910   ///
 2911   /// If `descendant` is provided, that [RenderObject] is made visible. If
 2912   /// `descendant` is omitted, this [RenderObject] is made visible.
 2913   ///
 2914   /// The optional `rect` parameter describes which area of that [RenderObject]
 2915   /// should be shown on screen. If `rect` is null, the entire
 2916   /// [RenderObject] (as defined by its [paintBounds]) will be revealed. The
 2917   /// `rect` parameter is interpreted relative to the coordinate system of
 2918   /// `descendant` if that argument is provided and relative to this
 2919   /// [RenderObject] otherwise.
 2920   ///
 2921   /// The `duration` parameter can be set to a non-zero value to bring the
 2922   /// target object on screen in an animation defined by `curve`.
 2923   ///
 2924   /// See also:
 2925   ///
 2926   /// * [RenderViewportBase.showInViewport], which [RenderViewportBase] and
 2927   ///   [SingleChildScrollView] delegate this method to.
 2928   void showOnScreen({
 2929     RenderObject? descendant,
 2930     Rect? rect,
 2931     Duration duration = Duration.zero,
 2932     Curve curve = Curves.ease,
 2933   }) {
 2934     if (parent is RenderObject) {
 2935       final RenderObject renderParent = parent as RenderObject;
 2936       renderParent.showOnScreen(
 2937         descendant: descendant ?? this,
 2938         rect: rect,
 2939         duration: duration,
 2940         curve: curve,
 2941       );
 2942     }
 2943   }
 2944 
 2945   /// Adds a debug representation of a [RenderObject] optimized for including in
 2946   /// error messages.
 2947   ///
 2948   /// The default [style] of [DiagnosticsTreeStyle.shallow] ensures that all of
 2949   /// the properties of the render object are included in the error output but
 2950   /// none of the children of the object are.
 2951   ///
 2952   /// You should always include a RenderObject in an error message if it is the
 2953   /// [RenderObject] causing the failure or contract violation of the error.
 2954   DiagnosticsNode describeForError(String name, { DiagnosticsTreeStyle style = DiagnosticsTreeStyle.shallow }) {
 2955     return toDiagnosticsNode(name: name, style: style);
 2956   }
 2957 }
 2958 
 2959 /// Generic mixin for render objects with one child.
 2960 ///
 2961 /// Provides a child model for a render object subclass that has
 2962 /// a unique child, which is accessible via the [child] getter.
 2963 ///
 2964 /// This mixin is typically used to implement render objects created
 2965 /// in a [SingleChildRenderObjectWidget].
 2966 mixin RenderObjectWithChildMixin<ChildType extends RenderObject> on RenderObject {
 2967 
 2968   /// Checks whether the given render object has the correct [runtimeType] to be
 2969   /// a child of this render object.
 2970   ///
 2971   /// Does nothing if assertions are disabled.
 2972   ///
 2973   /// Always returns true.
 2974   bool debugValidateChild(RenderObject child) {
 2975     assert(() {
 2976       if (child is! ChildType) {
 2977         throw FlutterError.fromParts(<DiagnosticsNode>[
 2978           ErrorSummary(
 2979             'A $runtimeType expected a child of type $ChildType but received a '
 2980             'child of type ${child.runtimeType}.'
 2981           ),
 2982           ErrorDescription(
 2983             'RenderObjects expect specific types of children because they '
 2984             'coordinate with their children during layout and paint. For '
 2985             'example, a RenderSliver cannot be the child of a RenderBox because '
 2986             'a RenderSliver does not understand the RenderBox layout protocol.',
 2987           ),
 2988           ErrorSpacer(),
 2989           DiagnosticsProperty<Object?>(
 2990             'The $runtimeType that expected a $ChildType child was created by',
 2991             debugCreator,
 2992             style: DiagnosticsTreeStyle.errorProperty,
 2993           ),
 2994           ErrorSpacer(),
 2995           DiagnosticsProperty<Object?>(
 2996             'The ${child.runtimeType} that did not match the expected child type '
 2997             'was created by',
 2998             child.debugCreator,
 2999             style: DiagnosticsTreeStyle.errorProperty,
 3000           ),
 3001         ]);
 3002       }
 3003       return true;
 3004     }());
 3005     return true;
 3006   }
 3007 
 3008   ChildType? _child;
 3009   /// The render object's unique child.
 3010   ChildType? get child => _child;
 3011   set child(ChildType? value) {
 3012     if (_child != null)
 3013       dropChild(_child!);
 3014     _child = value;
 3015     if (_child != null)
 3016       adoptChild(_child!);
 3017   }
 3018 
 3019   @override
 3020   void attach(PipelineOwner owner) {
 3021     super.attach(owner);
 3022     if (_child != null)
 3023       _child!.attach(owner);
 3024   }
 3025 
 3026   @override
 3027   void detach() {
 3028     super.detach();
 3029     if (_child != null)
 3030       _child!.detach();
 3031   }
 3032 
 3033   @override
 3034   void redepthChildren() {
 3035     if (_child != null)
 3036       redepthChild(_child!);
 3037   }
 3038 
 3039   @override
 3040   void visitChildren(RenderObjectVisitor visitor) {
 3041     if (_child != null)
 3042       visitor(_child!);
 3043   }
 3044 
 3045   @override
 3046   List<DiagnosticsNode> debugDescribeChildren() {
 3047     return child != null ? <DiagnosticsNode>[child!.toDiagnosticsNode(name: 'child')] : <DiagnosticsNode>[];
 3048   }
 3049 }
 3050 
 3051 /// Parent data to support a doubly-linked list of children.
 3052 ///
 3053 /// The children can be traversed using [nextSibling] or [previousSibling],
 3054 /// which can be called on the parent data of the render objects
 3055 /// obtained via [ContainerRenderObjectMixin.firstChild] or
 3056 /// [ContainerRenderObjectMixin.lastChild].
 3057 mixin ContainerParentDataMixin<ChildType extends RenderObject> on ParentData {
 3058   /// The previous sibling in the parent's child list.
 3059   ChildType? previousSibling;
 3060   /// The next sibling in the parent's child list.
 3061   ChildType? nextSibling;
 3062 
 3063   /// Clear the sibling pointers.
 3064   @override
 3065   void detach() {
 3066     assert(previousSibling == null, 'Pointers to siblings must be nulled before detaching ParentData.');
 3067     assert(nextSibling == null, 'Pointers to siblings must be nulled before detaching ParentData.');
 3068     super.detach();
 3069   }
 3070 }
 3071 
 3072 /// Generic mixin for render objects with a list of children.
 3073 ///
 3074 /// Provides a child model for a render object subclass that has a doubly-linked
 3075 /// list of children.
 3076 ///
 3077 /// The [ChildType] specifies the type of the children (extending [RenderObject]),
 3078 /// e.g. [RenderBox].
 3079 ///
 3080 /// [ParentDataType] stores parent container data on its child render objects.
 3081 /// It must extend [ContainerParentDataMixin], which provides the interface
 3082 /// for visiting children. This data is populated by
 3083 /// [RenderObject.setupParentData] implemented by the class using this mixin.
 3084 ///
 3085 /// When using [RenderBox] as the child type, you will usually want to make use of
 3086 /// [RenderBoxContainerDefaultsMixin] and extend [ContainerBoxParentData] for the
 3087 /// parent data.
 3088 ///
 3089 /// Moreover, this is a required mixin for render objects returned to [MultiChildRenderObjectWidget].
 3090 mixin ContainerRenderObjectMixin<ChildType extends RenderObject, ParentDataType extends ContainerParentDataMixin<ChildType>> on RenderObject {
 3091   bool _debugUltimatePreviousSiblingOf(ChildType child, { ChildType? equals }) {
 3092     ParentDataType childParentData = child.parentData as ParentDataType;
 3093     while (childParentData.previousSibling != null) {
 3094       assert(childParentData.previousSibling != child);
 3095       child = childParentData.previousSibling!;
 3096       childParentData = child.parentData as ParentDataType;
 3097     }
 3098     return child == equals;
 3099   }
 3100   bool _debugUltimateNextSiblingOf(ChildType child, { ChildType? equals }) {
 3101     ParentDataType childParentData = child.parentData as ParentDataType;
 3102     while (childParentData.nextSibling != null) {
 3103       assert(childParentData.nextSibling != child);
 3104       child = childParentData.nextSibling!;
 3105       childParentData = child.parentData as ParentDataType;
 3106     }
 3107     return child == equals;
 3108   }
 3109 
 3110   int _childCount = 0;
 3111   /// The number of children.
 3112   int get childCount => _childCount;
 3113 
 3114   /// Checks whether the given render object has the correct [runtimeType] to be
 3115   /// a child of this render object.
 3116   ///
 3117   /// Does nothing if assertions are disabled.
 3118   ///
 3119   /// Always returns true.
 3120   bool debugValidateChild(RenderObject child) {
 3121     assert(() {
 3122       if (child is! ChildType) {
 3123         throw FlutterError.fromParts(<DiagnosticsNode>[
 3124           ErrorSummary(
 3125             'A $runtimeType expected a child of type $ChildType but received a '
 3126             'child of type ${child.runtimeType}.'
 3127           ),
 3128           ErrorDescription(
 3129             'RenderObjects expect specific types of children because they '
 3130             'coordinate with their children during layout and paint. For '
 3131             'example, a RenderSliver cannot be the child of a RenderBox because '
 3132             'a RenderSliver does not understand the RenderBox layout protocol.'
 3133           ),
 3134           ErrorSpacer(),
 3135           DiagnosticsProperty<Object?>(
 3136             'The $runtimeType that expected a $ChildType child was created by',
 3137             debugCreator,
 3138             style: DiagnosticsTreeStyle.errorProperty,
 3139           ),
 3140           ErrorSpacer(),
 3141           DiagnosticsProperty<Object?>(
 3142             'The ${child.runtimeType} that did not match the expected child type '
 3143             'was created by',
 3144             child.debugCreator,
 3145             style: DiagnosticsTreeStyle.errorProperty,
 3146           ),
 3147         ]);
 3148       }
 3149       return true;
 3150     }());
 3151     return true;
 3152   }
 3153 
 3154   ChildType? _firstChild;
 3155   ChildType? _lastChild;
 3156   void _insertIntoChildList(ChildType child, { ChildType? after }) {
 3157     final ParentDataType childParentData = child.parentData as ParentDataType;
 3158     assert(childParentData.nextSibling == null);
 3159     assert(childParentData.previousSibling == null);
 3160     _childCount += 1;
 3161     assert(_childCount > 0);
 3162     if (after == null) {
 3163       // insert at the start (_firstChild)
 3164       childParentData.nextSibling = _firstChild;
 3165       if (_firstChild != null) {
 3166         final ParentDataType _firstChildParentData = _firstChild!.parentData as ParentDataType;
 3167         _firstChildParentData.previousSibling = child;
 3168       }
 3169       _firstChild = child;
 3170       _lastChild ??= child;
 3171     } else {
 3172       assert(_firstChild != null);
 3173       assert(_lastChild != null);
 3174       assert(_debugUltimatePreviousSiblingOf(after, equals: _firstChild));
 3175       assert(_debugUltimateNextSiblingOf(after, equals: _lastChild));
 3176       final ParentDataType afterParentData = after.parentData as ParentDataType;
 3177       if (afterParentData.nextSibling == null) {
 3178         // insert at the end (_lastChild); we'll end up with two or more children
 3179         assert(after == _lastChild);
 3180         childParentData.previousSibling = after;
 3181         afterParentData.nextSibling = child;
 3182         _lastChild = child;
 3183       } else {
 3184         // insert in the middle; we'll end up with three or more children
 3185         // set up links from child to siblings
 3186         childParentData.nextSibling = afterParentData.nextSibling;
 3187         childParentData.previousSibling = after;
 3188         // set up links from siblings to child
 3189         final ParentDataType childPreviousSiblingParentData = childParentData.previousSibling!.parentData as ParentDataType;
 3190         final ParentDataType childNextSiblingParentData = childParentData.nextSibling!.parentData as ParentDataType;
 3191         childPreviousSiblingParentData.nextSibling = child;
 3192         childNextSiblingParentData.previousSibling = child;
 3193         assert(afterParentData.nextSibling == child);
 3194       }
 3195     }
 3196   }
 3197   /// Insert child into this render object's child list after the given child.
 3198   ///
 3199   /// If `after` is null, then this inserts the child at the start of the list,
 3200   /// and the child becomes the new [firstChild].
 3201   void insert(ChildType child, { ChildType? after }) {
 3202     assert(child != this, 'A RenderObject cannot be inserted into itself.');
 3203     assert(after != this, 'A RenderObject cannot simultaneously be both the parent and the sibling of another RenderObject.');
 3204     assert(child != after, 'A RenderObject cannot be inserted after itself.');
 3205     assert(child != _firstChild);
 3206     assert(child != _lastChild);
 3207     adoptChild(child);
 3208     _insertIntoChildList(child, after: after);
 3209   }
 3210 
 3211   /// Append child to the end of this render object's child list.
 3212   void add(ChildType child) {
 3213     insert(child, after: _lastChild);
 3214   }
 3215 
 3216   /// Add all the children to the end of this render object's child list.
 3217   void addAll(List<ChildType>? children) {
 3218     children?.forEach(add);
 3219   }
 3220 
 3221   void _removeFromChildList(ChildType child) {
 3222     final ParentDataType childParentData = child.parentData as ParentDataType;
 3223     assert(_debugUltimatePreviousSiblingOf(child, equals: _firstChild));
 3224     assert(_debugUltimateNextSiblingOf(child, equals: _lastChild));
 3225     assert(_childCount >= 0);
 3226     if (childParentData.previousSibling == null) {
 3227       assert(_firstChild == child);
 3228       _firstChild = childParentData.nextSibling;
 3229     } else {
 3230       final ParentDataType childPreviousSiblingParentData = childParentData.previousSibling!.parentData as ParentDataType;
 3231       childPreviousSiblingParentData.nextSibling = childParentData.nextSibling;
 3232     }
 3233     if (childParentData.nextSibling == null) {
 3234       assert(_lastChild == child);
 3235       _lastChild = childParentData.previousSibling;
 3236     } else {
 3237       final ParentDataType childNextSiblingParentData = childParentData.nextSibling!.parentData as ParentDataType;
 3238       childNextSiblingParentData.previousSibling = childParentData.previousSibling;
 3239     }
 3240     childParentData.previousSibling = null;
 3241     childParentData.nextSibling = null;
 3242     _childCount -= 1;
 3243   }
 3244 
 3245   /// Remove this child from the child list.
 3246   ///
 3247   /// Requires the child to be present in the child list.
 3248   void remove(ChildType child) {
 3249     _removeFromChildList(child);
 3250     dropChild(child);
 3251   }
 3252 
 3253   /// Remove all their children from this render object's child list.
 3254   ///
 3255   /// More efficient than removing them individually.
 3256   void removeAll() {
 3257     ChildType? child = _firstChild;
 3258     while (child != null) {
 3259       final ParentDataType childParentData = child.parentData as ParentDataType;
 3260       final ChildType? next = childParentData.nextSibling;
 3261       childParentData.previousSibling = null;
 3262       childParentData.nextSibling = null;
 3263       dropChild(child);
 3264       child = next;
 3265     }
 3266     _firstChild = null;
 3267     _lastChild = null;
 3268     _childCount = 0;
 3269   }
 3270 
 3271   /// Move the given `child` in the child list to be after another child.
 3272   ///
 3273   /// More efficient than removing and re-adding the child. Requires the child
 3274   /// to already be in the child list at some position. Pass null for `after` to
 3275   /// move the child to the start of the child list.
 3276   void move(ChildType child, { ChildType? after }) {
 3277     assert(child != this);
 3278     assert(after != this);
 3279     assert(child != after);
 3280     assert(child.parent == this);
 3281     final ParentDataType childParentData = child.parentData as ParentDataType;
 3282     if (childParentData.previousSibling == after)
 3283       return;
 3284     _removeFromChildList(child);
 3285     _insertIntoChildList(child, after: after);
 3286     markNeedsLayout();
 3287   }
 3288 
 3289   @override
 3290   void attach(PipelineOwner owner) {
 3291     super.attach(owner);
 3292     ChildType? child = _firstChild;
 3293     while (child != null) {
 3294       child.attach(owner);
 3295       final ParentDataType childParentData = child.parentData as ParentDataType;
 3296       child = childParentData.nextSibling;
 3297     }
 3298   }
 3299 
 3300   @override
 3301   void detach() {
 3302     super.detach();
 3303     ChildType? child = _firstChild;
 3304     while (child != null) {
 3305       child.detach();
 3306       final ParentDataType childParentData = child.parentData as ParentDataType;
 3307       child = childParentData.nextSibling;
 3308     }
 3309   }
 3310 
 3311   @override
 3312   void redepthChildren() {
 3313     ChildType? child = _firstChild;
 3314     while (child != null) {
 3315       redepthChild(child);
 3316       final ParentDataType childParentData = child.parentData as ParentDataType;
 3317       child = childParentData.nextSibling;
 3318     }
 3319   }
 3320 
 3321   @override
 3322   void visitChildren(RenderObjectVisitor visitor) {
 3323     ChildType? child = _firstChild;
 3324     while (child != null) {
 3325       visitor(child);
 3326       final ParentDataType childParentData = child.parentData as ParentDataType;
 3327       child = childParentData.nextSibling;
 3328     }
 3329   }
 3330 
 3331   /// The first child in the child list.
 3332   ChildType? get firstChild => _firstChild;
 3333 
 3334   /// The last child in the child list.
 3335   ChildType? get lastChild => _lastChild;
 3336 
 3337   /// The previous child before the given child in the child list.
 3338   ChildType? childBefore(ChildType child) {
 3339     assert(child != null);
 3340     assert(child.parent == this);
 3341     final ParentDataType childParentData = child.parentData as ParentDataType;
 3342     return childParentData.previousSibling;
 3343   }
 3344 
 3345   /// The next child after the given child in the child list.
 3346   ChildType? childAfter(ChildType child) {
 3347     assert(child != null);
 3348     assert(child.parent == this);
 3349     final ParentDataType childParentData = child.parentData as ParentDataType;
 3350     return childParentData.nextSibling;
 3351   }
 3352 
 3353   @override
 3354   List<DiagnosticsNode> debugDescribeChildren() {
 3355     final List<DiagnosticsNode> children = <DiagnosticsNode>[];
 3356     if (firstChild != null) {
 3357       ChildType child = firstChild!;
 3358       int count = 1;
 3359       while (true) {
 3360         children.add(child.toDiagnosticsNode(name: 'child $count'));
 3361         if (child == lastChild)
 3362           break;
 3363         count += 1;
 3364         final ParentDataType childParentData = child.parentData as ParentDataType;
 3365         child = childParentData.nextSibling!;
 3366       }
 3367     }
 3368     return children;
 3369   }
 3370 }
 3371 
 3372 /// Mixin for [RenderObject] that will call [systemFontsDidChange] whenever the
 3373 /// system fonts change.
 3374 ///
 3375 /// System fonts can change when the OS install or remove a font. Use this mixin if
 3376 /// the [RenderObject] uses [TextPainter] or [Paragraph] to correctly update the
 3377 /// text when it happens.
 3378 mixin RelayoutWhenSystemFontsChangeMixin on RenderObject {
 3379 
 3380   /// A callback that is called when system fonts have changed.
 3381   ///
 3382   /// By default, [markNeedsLayout] is called on the [RenderObject]
 3383   /// implementing this mixin.
 3384   ///
 3385   /// Subclass should override this method to clear any extra cache that depend
 3386   /// on font-related metrics.
 3387   @protected
 3388   @mustCallSuper
 3389   void systemFontsDidChange() {
 3390     markNeedsLayout();
 3391   }
 3392 
 3393   @override
 3394   void attach(covariant PipelineOwner owner) {
 3395     super.attach(owner);
 3396     PaintingBinding.instance!.systemFonts.addListener(systemFontsDidChange);
 3397   }
 3398 
 3399   @override
 3400   void detach() {
 3401     PaintingBinding.instance!.systemFonts.removeListener(systemFontsDidChange);
 3402     super.detach();
 3403   }
 3404 }
 3405 
 3406 /// Describes the semantics information a [RenderObject] wants to add to its
 3407 /// parent.
 3408 ///
 3409 /// It has two notable subclasses:
 3410 ///  * [_InterestingSemanticsFragment] describing actual semantic information to
 3411 ///    be added to the parent.
 3412 ///  * [_ContainerSemanticsFragment]: a container class to transport the semantic
 3413 ///    information of multiple [_InterestingSemanticsFragment] to a parent.
 3414 abstract class _SemanticsFragment {
 3415   _SemanticsFragment({ required this.dropsSemanticsOfPreviousSiblings })
 3416     : assert (dropsSemanticsOfPreviousSiblings != null);
 3417 
 3418   /// Incorporate the fragments of children into this fragment.
 3419   void addAll(Iterable<_InterestingSemanticsFragment> fragments);
 3420 
 3421   /// Whether this fragment wants to make the semantics information of
 3422   /// previously painted [RenderObject]s unreachable for accessibility purposes.
 3423   ///
 3424   /// See also:
 3425   ///
 3426   ///  * [SemanticsConfiguration.isBlockingSemanticsOfPreviouslyPaintedNodes]
 3427   ///    describes what semantics are dropped in more detail.
 3428   final bool dropsSemanticsOfPreviousSiblings;
 3429 
 3430   /// Returns [_InterestingSemanticsFragment] describing the actual semantic
 3431   /// information that this fragment wants to add to the parent.
 3432   List<_InterestingSemanticsFragment> get interestingFragments;
 3433 
 3434   /// Whether this fragment wants to abort the semantics walk because the
 3435   /// information in the tree are not sufficient to calculate semantics.
 3436   ///
 3437   /// This happens for subtrees that are currently kept alive by a viewport but
 3438   /// not laid out.
 3439   ///
 3440   /// See also:
 3441   ///
 3442   ///  * [_AbortingSemanticsFragment], which sets this to true.
 3443   bool get abortsWalk => false;
 3444 }
 3445 
 3446 /// A container used when a [RenderObject] wants to add multiple independent
 3447 /// [_InterestingSemanticsFragment] to its parent.
 3448 ///
 3449 /// The [_InterestingSemanticsFragment] to be added to the parent can be
 3450 /// obtained via [interestingFragments].
 3451 class _ContainerSemanticsFragment extends _SemanticsFragment {
 3452 
 3453   _ContainerSemanticsFragment({ required bool dropsSemanticsOfPreviousSiblings })
 3454     : super(dropsSemanticsOfPreviousSiblings: dropsSemanticsOfPreviousSiblings);
 3455 
 3456   @override
 3457   void addAll(Iterable<_InterestingSemanticsFragment> fragments) {
 3458     interestingFragments.addAll(fragments);
 3459   }
 3460 
 3461   @override
 3462   final List<_InterestingSemanticsFragment> interestingFragments = <_InterestingSemanticsFragment>[];
 3463 }
 3464 
 3465 /// A [_SemanticsFragment] that describes which concrete semantic information
 3466 /// a [RenderObject] wants to add to the [SemanticsNode] of its parent.
 3467 ///
 3468 /// Specifically, it describes which children (as returned by [compileChildren])
 3469 /// should be added to the parent's [SemanticsNode] and which [config] should be
 3470 /// merged into the parent's [SemanticsNode].
 3471 abstract class _InterestingSemanticsFragment extends _SemanticsFragment {
 3472   _InterestingSemanticsFragment({
 3473     required RenderObject owner,
 3474     required bool dropsSemanticsOfPreviousSiblings,
 3475   }) : assert(owner != null),
 3476        _ancestorChain = <RenderObject>[owner],
 3477        super(dropsSemanticsOfPreviousSiblings: dropsSemanticsOfPreviousSiblings);
 3478 
 3479   /// The [RenderObject] that owns this fragment (and any new [SemanticsNode]
 3480   /// introduced by it).
 3481   RenderObject get owner => _ancestorChain.first;
 3482 
 3483   final List<RenderObject> _ancestorChain;
 3484 
 3485   /// The children to be added to the parent.
 3486   ///
 3487   /// See also:
 3488   ///
 3489   ///  * [SemanticsNode.parentSemanticsClipRect] for the source and definition
 3490   ///    of the `parentSemanticsClipRect` argument.
 3491   ///  * [SemanticsNode.parentPaintClipRect] for the source and definition
 3492   //     of the `parentPaintClipRect` argument.
 3493   ///  * [SemanticsNode.elevationAdjustment] for the source and definition
 3494   //    of the `elevationAdjustment` argument.
 3495   void compileChildren({
 3496     required Rect? parentSemanticsClipRect,
 3497     required Rect? parentPaintClipRect,
 3498     required double elevationAdjustment,
 3499     required List<SemanticsNode> result,
 3500   });
 3501 
 3502   /// The [SemanticsConfiguration] the child wants to merge into the parent's
 3503   /// [SemanticsNode] or null if it doesn't want to merge anything.
 3504   SemanticsConfiguration? get config;
 3505 
 3506   /// Disallows this fragment to merge any configuration into its parent's
 3507   /// [SemanticsNode].
 3508   ///
 3509   /// After calling this the fragment will only produce children to be added
 3510   /// to the parent and it will return null for [config].
 3511   void markAsExplicit();
 3512 
 3513   /// Consume the fragments of children.
 3514   ///
 3515   /// For each provided fragment it will add that fragment's children to
 3516   /// this fragment's children (as returned by [compileChildren]) and merge that
 3517   /// fragment's [config] into this fragment's [config].
 3518   ///
 3519   /// If a provided fragment should not merge anything into [config] call
 3520   /// [markAsExplicit] before passing the fragment to this method.
 3521   @override
 3522   void addAll(Iterable<_InterestingSemanticsFragment> fragments);
 3523 
 3524   /// Whether this fragment wants to add any semantic information to the parent
 3525   /// [SemanticsNode].
 3526   bool get hasConfigForParent => config != null;
 3527 
 3528   @override
 3529   List<_InterestingSemanticsFragment> get interestingFragments => <_InterestingSemanticsFragment>[this];
 3530 
 3531   Set<SemanticsTag>? _tagsForChildren;
 3532 
 3533   /// Tag all children produced by [compileChildren] with `tags`.
 3534   void addTags(Iterable<SemanticsTag>? tags) {
 3535     if (tags == null || tags.isEmpty)
 3536       return;
 3537     _tagsForChildren ??= <SemanticsTag>{};
 3538     _tagsForChildren!.addAll(tags);
 3539   }
 3540 
 3541   /// Adds the geometric information of `ancestor` to this object.
 3542   ///
 3543   /// Those information are required to properly compute the value for
 3544   /// [SemanticsNode.transform], [SemanticsNode.clipRect], and
 3545   /// [SemanticsNode.rect].
 3546   ///
 3547   /// Ancestors have to be added in order from [owner] up until the next
 3548   /// [RenderObject] that owns a [SemanticsNode] is reached.
 3549   void addAncestor(RenderObject ancestor) {
 3550     _ancestorChain.add(ancestor);
 3551   }
 3552 }
 3553 
 3554 /// An [_InterestingSemanticsFragment] that produces the root [SemanticsNode] of
 3555 /// the semantics tree.
 3556 ///
 3557 /// The root node is available as the only element in the Iterable returned by
 3558 /// [children].
 3559 class _RootSemanticsFragment extends _InterestingSemanticsFragment {
 3560   _RootSemanticsFragment({
 3561     required RenderObject owner,
 3562     required bool dropsSemanticsOfPreviousSiblings,
 3563   }) : super(owner: owner, dropsSemanticsOfPreviousSiblings: dropsSemanticsOfPreviousSiblings);
 3564 
 3565   @override
 3566   void compileChildren({ Rect? parentSemanticsClipRect, Rect? parentPaintClipRect, required double elevationAdjustment, required List<SemanticsNode> result }) {
 3567     assert(_tagsForChildren == null || _tagsForChildren!.isEmpty);
 3568     assert(parentSemanticsClipRect == null);
 3569     assert(parentPaintClipRect == null);
 3570     assert(_ancestorChain.length == 1);
 3571     assert(elevationAdjustment == 0.0);
 3572 
 3573     owner._semantics ??= SemanticsNode.root(
 3574       showOnScreen: owner.showOnScreen,
 3575       owner: owner.owner!.semanticsOwner!,
 3576     );
 3577     final SemanticsNode node = owner._semantics!;
 3578     assert(MatrixUtils.matrixEquals(node.transform, Matrix4.identity()));
 3579     assert(node.parentSemanticsClipRect == null);
 3580     assert(node.parentPaintClipRect == null);
 3581 
 3582     node.rect = owner.semanticBounds;
 3583 
 3584     final List<SemanticsNode> children = <SemanticsNode>[];
 3585     for (final _InterestingSemanticsFragment fragment in _children) {
 3586       assert(fragment.config == null);
 3587       fragment.compileChildren(
 3588         parentSemanticsClipRect: parentSemanticsClipRect,
 3589         parentPaintClipRect: parentPaintClipRect,
 3590         elevationAdjustment: 0.0,
 3591         result: children,
 3592       );
 3593     }
 3594     node.updateWith(config: null, childrenInInversePaintOrder: children);
 3595 
 3596     // The root node is the only semantics node allowed to be invisible. This
 3597     // can happen when the canvas the app is drawn on has a size of 0 by 0
 3598     // pixel. If this happens, the root node must not have any children (because
 3599     // these would be invisible as well and are therefore excluded from the
 3600     // tree).
 3601     assert(!node.isInvisible || children.isEmpty);
 3602     result.add(node);
 3603   }
 3604 
 3605   @override
 3606   SemanticsConfiguration? get config => null;
 3607 
 3608   final List<_InterestingSemanticsFragment> _children = <_InterestingSemanticsFragment>[];
 3609 
 3610   @override
 3611   void markAsExplicit() {
 3612     // nothing to do, we are always explicit.
 3613   }
 3614 
 3615   @override
 3616   void addAll(Iterable<_InterestingSemanticsFragment> fragments) {
 3617     _children.addAll(fragments);
 3618   }
 3619 }
 3620 
 3621 /// An [_InterestingSemanticsFragment] that can be told to only add explicit
 3622 /// [SemanticsNode]s to the parent.
 3623 ///
 3624 /// If [markAsExplicit] was not called before this fragment is added to
 3625 /// another fragment it will merge [config] into the parent's [SemanticsNode]
 3626 /// and add its [children] to it.
 3627 ///
 3628 /// If [markAsExplicit] was called before adding this fragment to another
 3629 /// fragment it will create a new [SemanticsNode]. The newly created node will
 3630 /// be annotated with the [SemanticsConfiguration] that - without the call to
 3631 /// [markAsExplicit] - would have been merged into the parent's [SemanticsNode].
 3632 /// Similarly, the new node will also take over the children that otherwise
 3633 /// would have been added to the parent's [SemanticsNode].
 3634 ///
 3635 /// After a call to [markAsExplicit] the only element returned by [children]
 3636 /// is the newly created node and [config] will return null as the fragment
 3637 /// no longer wants to merge any semantic information into the parent's
 3638 /// [SemanticsNode].
 3639 class _SwitchableSemanticsFragment extends _InterestingSemanticsFragment {
 3640   _SwitchableSemanticsFragment({
 3641     required bool mergeIntoParent,
 3642     required SemanticsConfiguration config,
 3643     required RenderObject owner,
 3644     required bool dropsSemanticsOfPreviousSiblings,
 3645   }) : _mergeIntoParent = mergeIntoParent,
 3646        _config = config,
 3647        assert(mergeIntoParent != null),
 3648        assert(config != null),
 3649        super(owner: owner, dropsSemanticsOfPreviousSiblings: dropsSemanticsOfPreviousSiblings);
 3650 
 3651   final bool _mergeIntoParent;
 3652   SemanticsConfiguration _config;
 3653   bool _isConfigWritable = false;
 3654   final List<_InterestingSemanticsFragment> _children = <_InterestingSemanticsFragment>[];
 3655 
 3656   @override
 3657   void compileChildren({ Rect? parentSemanticsClipRect, Rect? parentPaintClipRect, required double elevationAdjustment, required List<SemanticsNode> result }) {
 3658     if (!_isExplicit) {
 3659       owner._semantics = null;
 3660       for (final _InterestingSemanticsFragment fragment in _children) {
 3661         assert(_ancestorChain.first == fragment._ancestorChain.last);
 3662         fragment._ancestorChain.addAll(_ancestorChain.skip(1));
 3663         fragment.compileChildren(
 3664           parentSemanticsClipRect: parentSemanticsClipRect,
 3665           parentPaintClipRect: parentPaintClipRect,
 3666           // The fragment is not explicit, its elevation has been absorbed by
 3667           // the parent config (as thickness). We still need to make sure that
 3668           // its children are placed at the elevation dictated by this config.
 3669           elevationAdjustment: elevationAdjustment + _config.elevation,
 3670           result: result,
 3671         );
 3672       }
 3673       return;
 3674     }
 3675 
 3676     final _SemanticsGeometry? geometry = _needsGeometryUpdate
 3677         ? _SemanticsGeometry(parentSemanticsClipRect: parentSemanticsClipRect, parentPaintClipRect: parentPaintClipRect, ancestors: _ancestorChain)
 3678         : null;
 3679 
 3680     if (!_mergeIntoParent && (geometry?.dropFromTree == true))
 3681       return;  // Drop the node, it's not going to be visible.
 3682 
 3683     owner._semantics ??= SemanticsNode(showOnScreen: owner.showOnScreen);
 3684     final SemanticsNode node = owner._semantics!
 3685       ..isMergedIntoParent = _mergeIntoParent
 3686       ..tags = _tagsForChildren;
 3687 
 3688     node.elevationAdjustment = elevationAdjustment;
 3689     if (elevationAdjustment != 0.0) {
 3690       _ensureConfigIsWritable();
 3691       _config.elevation += elevationAdjustment;
 3692     }
 3693 
 3694     if (geometry != null) {
 3695       assert(_needsGeometryUpdate);
 3696       node
 3697         ..rect = geometry.rect
 3698         ..transform = geometry.transform
 3699         ..parentSemanticsClipRect = geometry.semanticsClipRect
 3700         ..parentPaintClipRect = geometry.paintClipRect;
 3701       if (!_mergeIntoParent && geometry.markAsHidden) {
 3702         _ensureConfigIsWritable();
 3703         _config.isHidden = true;
 3704       }
 3705     }
 3706 
 3707     final List<SemanticsNode> children = <SemanticsNode>[];
 3708     for (final _InterestingSemanticsFragment fragment in _children) {
 3709       fragment.compileChildren(
 3710         parentSemanticsClipRect: node.parentSemanticsClipRect,
 3711         parentPaintClipRect: node.parentPaintClipRect,
 3712         elevationAdjustment: 0.0,
 3713         result: children,
 3714       );
 3715     }
 3716     if (_config.isSemanticBoundary) {
 3717       owner.assembleSemanticsNode(node, _config, children);
 3718     } else {
 3719       node.updateWith(config: _config, childrenInInversePaintOrder: children);
 3720     }
 3721     result.add(node);
 3722   }
 3723 
 3724   @override
 3725   SemanticsConfiguration? get config {
 3726     return _isExplicit ? null : _config;
 3727   }
 3728 
 3729   @override
 3730   void addAll(Iterable<_InterestingSemanticsFragment> fragments) {
 3731     for (final _InterestingSemanticsFragment fragment in fragments) {
 3732       _children.add(fragment);
 3733       if (fragment.config == null)
 3734         continue;
 3735       _ensureConfigIsWritable();
 3736       _config.absorb(fragment.config!);
 3737     }
 3738   }
 3739 
 3740   void _ensureConfigIsWritable() {
 3741     if (!_isConfigWritable) {
 3742       _config = _config.copy();
 3743       _isConfigWritable = true;
 3744     }
 3745   }
 3746 
 3747   bool _isExplicit = false;
 3748 
 3749   @override
 3750   void markAsExplicit() {
 3751     _isExplicit = true;
 3752   }
 3753 
 3754   bool get _needsGeometryUpdate => _ancestorChain.length > 1;
 3755 }
 3756 
 3757 
 3758 /// [_SemanticsFragment] used to indicate that the current information in this
 3759 /// subtree is not sufficient to update semantics.
 3760 ///
 3761 /// Anybody processing this [_SemanticsFragment] should abort the walk of the
 3762 /// current subtree without updating any [SemanticsNode]s as there is no semantic
 3763 /// information to compute. As a result, this fragment also doesn't carry any
 3764 /// semantics information either.
 3765 class _AbortingSemanticsFragment extends _InterestingSemanticsFragment {
 3766   _AbortingSemanticsFragment({required RenderObject owner}) : super(owner: owner, dropsSemanticsOfPreviousSiblings: false);
 3767 
 3768   @override
 3769   bool get abortsWalk => true;
 3770 
 3771   @override
 3772   SemanticsConfiguration? get config => null;
 3773 
 3774   @override
 3775   void addAll(Iterable<_InterestingSemanticsFragment> fragments) {
 3776     assert(false);
 3777   }
 3778 
 3779   @override
 3780   void compileChildren({ Rect? parentSemanticsClipRect, Rect? parentPaintClipRect, required double elevationAdjustment, required List<SemanticsNode> result }) {
 3781     result.add(owner._semantics!);
 3782   }
 3783 
 3784   @override
 3785   void markAsExplicit() {
 3786     // Is never explicit.
 3787   }
 3788 }
 3789 
 3790 /// Helper class that keeps track of the geometry of a [SemanticsNode].
 3791 ///
 3792 /// It is used to annotate a [SemanticsNode] with the current information for
 3793 /// [SemanticsNode.rect] and [SemanticsNode.transform].
 3794 class _SemanticsGeometry {
 3795 
 3796   /// The `parentClippingRect` may be null if no clip is to be applied.
 3797   ///
 3798   /// The `ancestors` list has to include all [RenderObject] in order that are
 3799   /// located between the [SemanticsNode] whose geometry is represented here
 3800   /// (first [RenderObject] in the list) and its closest ancestor [RenderObject]
 3801   /// that also owns its own [SemanticsNode] (last [RenderObject] in the list).
 3802   _SemanticsGeometry({
 3803     required Rect? parentSemanticsClipRect,
 3804     required Rect? parentPaintClipRect,
 3805     required List<RenderObject> ancestors,
 3806   }) {
 3807     _computeValues(parentSemanticsClipRect, parentPaintClipRect, ancestors);
 3808   }
 3809 
 3810   Rect? _paintClipRect;
 3811   Rect? _semanticsClipRect;
 3812   late Matrix4 _transform;
 3813   late Rect _rect;
 3814 
 3815   /// Value for [SemanticsNode.transform].
 3816   Matrix4 get transform => _transform;
 3817 
 3818   /// Value for [SemanticsNode.parentSemanticsClipRect].
 3819   Rect? get semanticsClipRect => _semanticsClipRect;
 3820 
 3821   /// Value for [SemanticsNode.parentPaintClipRect].
 3822   Rect? get paintClipRect => _paintClipRect;
 3823 
 3824   /// Value for [SemanticsNode.rect].
 3825   Rect get rect => _rect;
 3826 
 3827   /// Computes values, ensuring `rect` is properly bounded by ancestor clipping rects.
 3828   ///
 3829   /// See also:
 3830   ///
 3831   /// * [RenderObject.describeSemanticsClip], typically used to determine `parentSemanticsClipRect`.
 3832   /// * [RenderObject.describeApproximatePaintClip], typically used to determine `parentPaintClipRect`.
 3833   void _computeValues(Rect? parentSemanticsClipRect, Rect? parentPaintClipRect, List<RenderObject> ancestors) {
 3834     assert(ancestors.length > 1);
 3835 
 3836     _transform = Matrix4.identity();
 3837     _semanticsClipRect = parentSemanticsClipRect;
 3838     _paintClipRect = parentPaintClipRect;
 3839     for (int index = ancestors.length-1; index > 0; index -= 1) {
 3840       final RenderObject parent = ancestors[index];
 3841       final RenderObject child = ancestors[index-1];
 3842       final Rect? parentSemanticsClipRect = parent.describeSemanticsClip(child);
 3843       if (parentSemanticsClipRect != null) {
 3844         _semanticsClipRect = parentSemanticsClipRect;
 3845         _paintClipRect = _intersectRects(_paintClipRect, parent.describeApproximatePaintClip(child));
 3846       } else {
 3847         _semanticsClipRect = _intersectRects(_semanticsClipRect, parent.describeApproximatePaintClip(child));
 3848       }
 3849       _temporaryTransformHolder.setIdentity(); // clears data from previous call(s)
 3850       _applyIntermediatePaintTransforms(parent, child, _transform, _temporaryTransformHolder);
 3851       _semanticsClipRect = _transformRect(_semanticsClipRect, _temporaryTransformHolder);
 3852       _paintClipRect = _transformRect(_paintClipRect, _temporaryTransformHolder);
 3853     }
 3854 
 3855     final RenderObject owner = ancestors.first;
 3856     _rect = _semanticsClipRect == null ? owner.semanticBounds : _semanticsClipRect!.intersect(owner.semanticBounds);
 3857     if (_paintClipRect != null) {
 3858       final Rect paintRect = _paintClipRect!.intersect(_rect);
 3859       _markAsHidden = paintRect.isEmpty && !_rect.isEmpty;
 3860       if (!_markAsHidden)
 3861         _rect = paintRect;
 3862     }
 3863   }
 3864 
 3865   // A matrix used to store transient transform data.
 3866   //
 3867   // Reusing this matrix avoids allocating a new matrix every time a temporary
 3868   // matrix is needed.
 3869   //
 3870   // This instance should never be returned to the caller. Otherwise, the data
 3871   // stored in it will be overwritten unpredictably by subsequent reuses.
 3872   static final Matrix4 _temporaryTransformHolder = Matrix4.zero();
 3873 
 3874   /// From parent to child coordinate system.
 3875   static Rect? _transformRect(Rect? rect, Matrix4 transform) {
 3876     assert(transform != null);
 3877     if (rect == null)
 3878       return null;
 3879     if (rect.isEmpty || transform.isZero())
 3880       return Rect.zero;
 3881     return MatrixUtils.inverseTransformRect(transform, rect);
 3882   }
 3883 
 3884   // Calls applyPaintTransform on all of the render objects between [child] and
 3885   // [ancestor]. This method handles cases where the immediate semantic parent
 3886   // is not the immediate render object parent of the child.
 3887   //
 3888   // It will mutate both transform and clipRectTransform.
 3889   static void _applyIntermediatePaintTransforms(
 3890     RenderObject ancestor,
 3891     RenderObject child,
 3892     Matrix4 transform,
 3893     Matrix4 clipRectTransform,
 3894   ) {
 3895     assert(ancestor != null);
 3896     assert(child != null);
 3897     assert(transform != null);
 3898     assert(clipRectTransform != null);
 3899     assert(clipRectTransform.isIdentity());
 3900     RenderObject intermediateParent = child.parent as RenderObject;
 3901     assert(intermediateParent != null);
 3902     while (intermediateParent != ancestor) {
 3903       intermediateParent.applyPaintTransform(child, transform);
 3904       intermediateParent = intermediateParent.parent as RenderObject;
 3905       child = child.parent as RenderObject;
 3906       assert(intermediateParent != null);
 3907     }
 3908     ancestor.applyPaintTransform(child, transform);
 3909     ancestor.applyPaintTransform(child, clipRectTransform);
 3910   }
 3911 
 3912   static Rect? _intersectRects(Rect? a, Rect? b) {
 3913     if (a == null)
 3914       return b;
 3915     if (b == null)
 3916       return a;
 3917     return a.intersect(b);
 3918   }
 3919 
 3920   /// Whether the [SemanticsNode] annotated with the geometric information tracked
 3921   /// by this object can be dropped from the semantics tree without losing
 3922   /// semantics information.
 3923   bool get dropFromTree {
 3924     return _rect.isEmpty;
 3925   }
 3926 
 3927   /// Whether the [SemanticsNode] annotated with the geometric information
 3928   /// tracked by this object should be marked as hidden because it is not
 3929   /// visible on screen.
 3930   ///
 3931   /// Hidden elements should still be included in the tree to work around
 3932   /// platform limitations (e.g. accessibility scrolling on iOS).
 3933   ///
 3934   /// See also:
 3935   ///
 3936   ///  * [SemanticsFlag.isHidden] for the purpose of marking a node as hidden.
 3937   bool get markAsHidden => _markAsHidden;
 3938   bool _markAsHidden = false;
 3939 }
 3940 
 3941 /// A class that creates [DiagnosticsNode] by wrapping [RenderObject.debugCreator].
 3942 ///
 3943 /// Attach a [DiagnosticsDebugCreator] into [FlutterErrorDetails.informationCollector]
 3944 /// when a [RenderObject.debugCreator] is available. This will lead to improved
 3945 /// error message.
 3946 class DiagnosticsDebugCreator extends DiagnosticsProperty<Object> {
 3947   /// Create a [DiagnosticsProperty] with its [value] initialized to input
 3948   /// [RenderObject.debugCreator].
 3949   DiagnosticsDebugCreator(Object value)
 3950     : assert(value != null),
 3951       super(
 3952         'debugCreator',
 3953         value,
 3954         level: DiagnosticLevel.hidden,
 3955       );
 3956 }