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/// @docImport 'package:flutter/widgets.dart';
6///
7/// @docImport 'image.dart';
8/// @docImport 'paragraph.dart';
9/// @docImport 'proxy_box.dart';
10/// @docImport 'shifted_box.dart';
11/// @docImport 'sliver.dart';
12/// @docImport 'viewport.dart';
13library;
14
15import 'dart:math' as math;
16import 'dart:ui' as ui show ViewConstraints, lerpDouble;
17
18import 'package:flutter/foundation.dart';
19import 'package:flutter/gestures.dart';
20import 'package:vector_math/vector_math_64.dart' show Matrix4, Vector3;
21
22import 'debug.dart';
23import 'object.dart';
24
25// Examples can assume:
26// abstract class RenderBar extends RenderBox { }
27// late RenderBox firstChild;
28// void markNeedsLayout() { }
29
30// This class should only be used in debug builds.
31class _DebugSize extends Size {
32 _DebugSize(super.source, this._owner, this._canBeUsedByParent) : super.copy();
33 final RenderBox _owner;
34 final bool _canBeUsedByParent;
35}
36
37/// Immutable layout constraints for [RenderBox] layout.
38///
39/// A [Size] respects a [BoxConstraints] if, and only if, all of the following
40/// relations hold:
41///
42/// * [minWidth] <= [Size.width] <= [maxWidth]
43/// * [minHeight] <= [Size.height] <= [maxHeight]
44///
45/// The constraints themselves must satisfy these relations:
46///
47/// * 0.0 <= [minWidth] <= [maxWidth] <= [double.infinity]
48/// * 0.0 <= [minHeight] <= [maxHeight] <= [double.infinity]
49///
50/// [double.infinity] is a legal value for each constraint.
51///
52/// ## The box layout model
53///
54/// Render objects in the Flutter framework are laid out by a one-pass layout
55/// model which walks down the render tree passing constraints, then walks back
56/// up the render tree passing concrete geometry.
57///
58/// For boxes, the constraints are [BoxConstraints], which, as described herein,
59/// consist of four numbers: a minimum width [minWidth], a maximum width
60/// [maxWidth], a minimum height [minHeight], and a maximum height [maxHeight].
61///
62/// The geometry for boxes consists of a [Size], which must satisfy the
63/// constraints described above.
64///
65/// Each [RenderBox] (the objects that provide the layout models for box
66/// widgets) receives [BoxConstraints] from its parent, then lays out each of
67/// its children, then picks a [Size] that satisfies the [BoxConstraints].
68///
69/// Render objects position their children independently of laying them out.
70/// Frequently, the parent will use the children's sizes to determine their
71/// position. A child does not know its position and will not necessarily be
72/// laid out again, or repainted, if its position changes.
73///
74/// ## Terminology
75///
76/// When the minimum constraints and the maximum constraint in an axis are the
77/// same, that axis is _tightly_ constrained. See: [
78/// BoxConstraints.tightFor], [BoxConstraints.tightForFinite], [tighten],
79/// [hasTightWidth], [hasTightHeight], [isTight].
80///
81/// An axis with a minimum constraint of 0.0 is _loose_ (regardless of the
82/// maximum constraint; if it is also 0.0, then the axis is simultaneously tight
83/// and loose!). See: [BoxConstraints.loose], [loosen].
84///
85/// An axis whose maximum constraint is not infinite is _bounded_. See:
86/// [hasBoundedWidth], [hasBoundedHeight].
87///
88/// An axis whose maximum constraint is infinite is _unbounded_. An axis is
89/// _expanding_ if it is tightly infinite (its minimum and maximum constraints
90/// are both infinite). See: [BoxConstraints.expand].
91///
92/// An axis whose _minimum_ constraint is infinite is just said to be _infinite_
93/// (since by definition the maximum constraint must also be infinite in that
94/// case). See: [hasInfiniteWidth], [hasInfiniteHeight].
95///
96/// A size is _constrained_ when it satisfies a [BoxConstraints] description.
97/// See: [constrain], [constrainWidth], [constrainHeight],
98/// [constrainDimensions], [constrainSizeAndAttemptToPreserveAspectRatio],
99/// [isSatisfiedBy].
100class BoxConstraints extends Constraints {
101 /// Creates box constraints with the given constraints.
102 const BoxConstraints({
103 this.minWidth = 0.0,
104 this.maxWidth = double.infinity,
105 this.minHeight = 0.0,
106 this.maxHeight = double.infinity,
107 });
108
109 /// Creates box constraints that is respected only by the given size.
110 BoxConstraints.tight(Size size)
111 : minWidth = size.width,
112 maxWidth = size.width,
113 minHeight = size.height,
114 maxHeight = size.height;
115
116 /// Creates box constraints that require the given width or height.
117 ///
118 /// See also:
119 ///
120 /// * [BoxConstraints.tightForFinite], which is similar but instead of
121 /// being tight if the value is non-null, is tight if the value is not
122 /// infinite.
123 const BoxConstraints.tightFor({double? width, double? height})
124 : minWidth = width ?? 0.0,
125 maxWidth = width ?? double.infinity,
126 minHeight = height ?? 0.0,
127 maxHeight = height ?? double.infinity;
128
129 /// Creates box constraints that require the given width or height, except if
130 /// they are infinite.
131 ///
132 /// See also:
133 ///
134 /// * [BoxConstraints.tightFor], which is similar but instead of being
135 /// tight if the value is not infinite, is tight if the value is non-null.
136 const BoxConstraints.tightForFinite({
137 double width = double.infinity,
138 double height = double.infinity,
139 }) : minWidth = width != double.infinity ? width : 0.0,
140 maxWidth = width != double.infinity ? width : double.infinity,
141 minHeight = height != double.infinity ? height : 0.0,
142 maxHeight = height != double.infinity ? height : double.infinity;
143
144 /// Creates box constraints that forbid sizes larger than the given size.
145 BoxConstraints.loose(Size size)
146 : minWidth = 0.0,
147 maxWidth = size.width,
148 minHeight = 0.0,
149 maxHeight = size.height;
150
151 /// Creates box constraints that expand to fill another box constraints.
152 ///
153 /// If width or height is given, the constraints will require exactly the
154 /// given value in the given dimension.
155 const BoxConstraints.expand({double? width, double? height})
156 : minWidth = width ?? double.infinity,
157 maxWidth = width ?? double.infinity,
158 minHeight = height ?? double.infinity,
159 maxHeight = height ?? double.infinity;
160
161 /// Creates box constraints that match the given view constraints.
162 BoxConstraints.fromViewConstraints(ui.ViewConstraints constraints)
163 : minWidth = constraints.minWidth,
164 maxWidth = constraints.maxWidth,
165 minHeight = constraints.minHeight,
166 maxHeight = constraints.maxHeight;
167
168 /// The minimum width that satisfies the constraints.
169 final double minWidth;
170
171 /// The maximum width that satisfies the constraints.
172 ///
173 /// Might be [double.infinity].
174 final double maxWidth;
175
176 /// The minimum height that satisfies the constraints.
177 final double minHeight;
178
179 /// The maximum height that satisfies the constraints.
180 ///
181 /// Might be [double.infinity].
182 final double maxHeight;
183
184 /// Creates a copy of this box constraints but with the given fields replaced with the new values.
185 BoxConstraints copyWith({
186 double? minWidth,
187 double? maxWidth,
188 double? minHeight,
189 double? maxHeight,
190 }) {
191 return BoxConstraints(
192 minWidth: minWidth ?? this.minWidth,
193 maxWidth: maxWidth ?? this.maxWidth,
194 minHeight: minHeight ?? this.minHeight,
195 maxHeight: maxHeight ?? this.maxHeight,
196 );
197 }
198
199 /// Returns new box constraints that are smaller by the given edge dimensions.
200 BoxConstraints deflate(EdgeInsetsGeometry edges) {
201 assert(debugAssertIsValid());
202 final double horizontal = edges.horizontal;
203 final double vertical = edges.vertical;
204 final double deflatedMinWidth = math.max(0.0, minWidth - horizontal);
205 final double deflatedMinHeight = math.max(0.0, minHeight - vertical);
206 return BoxConstraints(
207 minWidth: deflatedMinWidth,
208 maxWidth: math.max(deflatedMinWidth, maxWidth - horizontal),
209 minHeight: deflatedMinHeight,
210 maxHeight: math.max(deflatedMinHeight, maxHeight - vertical),
211 );
212 }
213
214 /// Returns new box constraints that remove the minimum width and height requirements.
215 BoxConstraints loosen() {
216 assert(debugAssertIsValid());
217 return BoxConstraints(maxWidth: maxWidth, maxHeight: maxHeight);
218 }
219
220 /// Returns new box constraints that respect the given constraints while being
221 /// as close as possible to the original constraints.
222 BoxConstraints enforce(BoxConstraints constraints) {
223 return BoxConstraints(
224 minWidth: clampDouble(minWidth, constraints.minWidth, constraints.maxWidth),
225 maxWidth: clampDouble(maxWidth, constraints.minWidth, constraints.maxWidth),
226 minHeight: clampDouble(minHeight, constraints.minHeight, constraints.maxHeight),
227 maxHeight: clampDouble(maxHeight, constraints.minHeight, constraints.maxHeight),
228 );
229 }
230
231 /// Returns new box constraints with a tight width and/or height as close to
232 /// the given width and height as possible while still respecting the original
233 /// box constraints.
234 BoxConstraints tighten({double? width, double? height}) {
235 return BoxConstraints(
236 minWidth: width == null ? minWidth : clampDouble(width, minWidth, maxWidth),
237 maxWidth: width == null ? maxWidth : clampDouble(width, minWidth, maxWidth),
238 minHeight: height == null ? minHeight : clampDouble(height, minHeight, maxHeight),
239 maxHeight: height == null ? maxHeight : clampDouble(height, minHeight, maxHeight),
240 );
241 }
242
243 /// A box constraints with the width and height constraints flipped.
244 BoxConstraints get flipped {
245 return BoxConstraints(
246 minWidth: minHeight,
247 maxWidth: maxHeight,
248 minHeight: minWidth,
249 maxHeight: maxWidth,
250 );
251 }
252
253 /// Returns box constraints with the same width constraints but with
254 /// unconstrained height.
255 BoxConstraints widthConstraints() => BoxConstraints(minWidth: minWidth, maxWidth: maxWidth);
256
257 /// Returns box constraints with the same height constraints but with
258 /// unconstrained width.
259 BoxConstraints heightConstraints() => BoxConstraints(minHeight: minHeight, maxHeight: maxHeight);
260
261 /// Returns the width that both satisfies the constraints and is as close as
262 /// possible to the given width.
263 double constrainWidth([double width = double.infinity]) {
264 assert(debugAssertIsValid());
265 return clampDouble(width, minWidth, maxWidth);
266 }
267
268 /// Returns the height that both satisfies the constraints and is as close as
269 /// possible to the given height.
270 double constrainHeight([double height = double.infinity]) {
271 assert(debugAssertIsValid());
272 return clampDouble(height, minHeight, maxHeight);
273 }
274
275 Size _debugPropagateDebugSize(Size size, Size result) {
276 assert(() {
277 if (size is _DebugSize) {
278 result = _DebugSize(result, size._owner, size._canBeUsedByParent);
279 }
280 return true;
281 }());
282 return result;
283 }
284
285 /// Returns the size that both satisfies the constraints and is as close as
286 /// possible to the given size.
287 ///
288 /// See also:
289 ///
290 /// * [constrainDimensions], which applies the same algorithm to
291 /// separately provided widths and heights.
292 Size constrain(Size size) {
293 Size result = Size(constrainWidth(size.width), constrainHeight(size.height));
294 assert(() {
295 result = _debugPropagateDebugSize(size, result);
296 return true;
297 }());
298 return result;
299 }
300
301 /// Returns the size that both satisfies the constraints and is as close as
302 /// possible to the given width and height.
303 ///
304 /// When you already have a [Size], prefer [constrain], which applies the same
305 /// algorithm to a [Size] directly.
306 Size constrainDimensions(double width, double height) {
307 return Size(constrainWidth(width), constrainHeight(height));
308 }
309
310 /// Returns a size that attempts to meet the following conditions, in order:
311 ///
312 /// * The size must satisfy these constraints.
313 /// * The aspect ratio of the returned size matches the aspect ratio of the
314 /// given size.
315 /// * The returned size is as big as possible while still being equal to or
316 /// smaller than the given size.
317 Size constrainSizeAndAttemptToPreserveAspectRatio(Size size) {
318 if (isTight) {
319 Size result = smallest;
320 assert(() {
321 result = _debugPropagateDebugSize(size, result);
322 return true;
323 }());
324 return result;
325 }
326
327 if (size.isEmpty) {
328 return constrain(size);
329 }
330
331 double width = size.width;
332 double height = size.height;
333 final double aspectRatio = width / height;
334
335 if (width > maxWidth) {
336 width = maxWidth;
337 height = width / aspectRatio;
338 }
339
340 if (height > maxHeight) {
341 height = maxHeight;
342 width = height * aspectRatio;
343 }
344
345 if (width < minWidth) {
346 width = minWidth;
347 height = width / aspectRatio;
348 }
349
350 if (height < minHeight) {
351 height = minHeight;
352 width = height * aspectRatio;
353 }
354
355 Size result = Size(constrainWidth(width), constrainHeight(height));
356 assert(() {
357 result = _debugPropagateDebugSize(size, result);
358 return true;
359 }());
360 return result;
361 }
362
363 /// The biggest size that satisfies the constraints.
364 Size get biggest => Size(constrainWidth(), constrainHeight());
365
366 /// The smallest size that satisfies the constraints.
367 Size get smallest => Size(constrainWidth(0.0), constrainHeight(0.0));
368
369 /// Whether there is exactly one width value that satisfies the constraints.
370 bool get hasTightWidth => minWidth >= maxWidth;
371
372 /// Whether there is exactly one height value that satisfies the constraints.
373 bool get hasTightHeight => minHeight >= maxHeight;
374
375 /// Whether there is exactly one size that satisfies the constraints.
376 @override
377 bool get isTight => hasTightWidth && hasTightHeight;
378
379 /// Whether there is an upper bound on the maximum width.
380 ///
381 /// See also:
382 ///
383 /// * [hasBoundedHeight], the equivalent for the vertical axis.
384 /// * [hasInfiniteWidth], which describes whether the minimum width
385 /// constraint is infinite.
386 bool get hasBoundedWidth => maxWidth < double.infinity;
387
388 /// Whether there is an upper bound on the maximum height.
389 ///
390 /// See also:
391 ///
392 /// * [hasBoundedWidth], the equivalent for the horizontal axis.
393 /// * [hasInfiniteHeight], which describes whether the minimum height
394 /// constraint is infinite.
395 bool get hasBoundedHeight => maxHeight < double.infinity;
396
397 /// Whether the width constraint is infinite.
398 ///
399 /// Such a constraint is used to indicate that a box should grow as large as
400 /// some other constraint (in this case, horizontally). If constraints are
401 /// infinite, then they must have other (non-infinite) constraints [enforce]d
402 /// upon them, or must be [tighten]ed, before they can be used to derive a
403 /// [Size] for a [RenderBox.size].
404 ///
405 /// See also:
406 ///
407 /// * [hasInfiniteHeight], the equivalent for the vertical axis.
408 /// * [hasBoundedWidth], which describes whether the maximum width
409 /// constraint is finite.
410 bool get hasInfiniteWidth => minWidth >= double.infinity;
411
412 /// Whether the height constraint is infinite.
413 ///
414 /// Such a constraint is used to indicate that a box should grow as large as
415 /// some other constraint (in this case, vertically). If constraints are
416 /// infinite, then they must have other (non-infinite) constraints [enforce]d
417 /// upon them, or must be [tighten]ed, before they can be used to derive a
418 /// [Size] for a [RenderBox.size].
419 ///
420 /// See also:
421 ///
422 /// * [hasInfiniteWidth], the equivalent for the horizontal axis.
423 /// * [hasBoundedHeight], which describes whether the maximum height
424 /// constraint is finite.
425 bool get hasInfiniteHeight => minHeight >= double.infinity;
426
427 /// Whether the given size satisfies the constraints.
428 bool isSatisfiedBy(Size size) {
429 assert(debugAssertIsValid());
430 return (minWidth <= size.width) &&
431 (size.width <= maxWidth) &&
432 (minHeight <= size.height) &&
433 (size.height <= maxHeight);
434 }
435
436 /// Scales each constraint parameter by the given factor.
437 BoxConstraints operator *(double factor) {
438 return BoxConstraints(
439 minWidth: minWidth * factor,
440 maxWidth: maxWidth * factor,
441 minHeight: minHeight * factor,
442 maxHeight: maxHeight * factor,
443 );
444 }
445
446 /// Scales each constraint parameter by the inverse of the given factor.
447 BoxConstraints operator /(double factor) {
448 return BoxConstraints(
449 minWidth: minWidth / factor,
450 maxWidth: maxWidth / factor,
451 minHeight: minHeight / factor,
452 maxHeight: maxHeight / factor,
453 );
454 }
455
456 /// Scales each constraint parameter by the inverse of the given factor, rounded to the nearest integer.
457 BoxConstraints operator ~/(double factor) {
458 return BoxConstraints(
459 minWidth: (minWidth ~/ factor).toDouble(),
460 maxWidth: (maxWidth ~/ factor).toDouble(),
461 minHeight: (minHeight ~/ factor).toDouble(),
462 maxHeight: (maxHeight ~/ factor).toDouble(),
463 );
464 }
465
466 /// Computes the remainder of each constraint parameter by the given value.
467 BoxConstraints operator %(double value) {
468 return BoxConstraints(
469 minWidth: minWidth % value,
470 maxWidth: maxWidth % value,
471 minHeight: minHeight % value,
472 maxHeight: maxHeight % value,
473 );
474 }
475
476 /// Linearly interpolate between two BoxConstraints.
477 ///
478 /// If either is null, this function interpolates from a [BoxConstraints]
479 /// object whose fields are all set to 0.0.
480 ///
481 /// {@macro dart.ui.shadow.lerp}
482 static BoxConstraints? lerp(BoxConstraints? a, BoxConstraints? b, double t) {
483 if (identical(a, b)) {
484 return a;
485 }
486 if (a == null) {
487 return b! * t;
488 }
489 if (b == null) {
490 return a * (1.0 - t);
491 }
492 assert(a.debugAssertIsValid());
493 assert(b.debugAssertIsValid());
494 assert(
495 (a.minWidth.isFinite && b.minWidth.isFinite) ||
496 (a.minWidth == double.infinity && b.minWidth == double.infinity),
497 'Cannot interpolate between finite constraints and unbounded constraints.',
498 );
499 assert(
500 (a.maxWidth.isFinite && b.maxWidth.isFinite) ||
501 (a.maxWidth == double.infinity && b.maxWidth == double.infinity),
502 'Cannot interpolate between finite constraints and unbounded constraints.',
503 );
504 assert(
505 (a.minHeight.isFinite && b.minHeight.isFinite) ||
506 (a.minHeight == double.infinity && b.minHeight == double.infinity),
507 'Cannot interpolate between finite constraints and unbounded constraints.',
508 );
509 assert(
510 (a.maxHeight.isFinite && b.maxHeight.isFinite) ||
511 (a.maxHeight == double.infinity && b.maxHeight == double.infinity),
512 'Cannot interpolate between finite constraints and unbounded constraints.',
513 );
514 return BoxConstraints(
515 minWidth: a.minWidth.isFinite ? ui.lerpDouble(a.minWidth, b.minWidth, t)! : double.infinity,
516 maxWidth: a.maxWidth.isFinite ? ui.lerpDouble(a.maxWidth, b.maxWidth, t)! : double.infinity,
517 minHeight: a.minHeight.isFinite
518 ? ui.lerpDouble(a.minHeight, b.minHeight, t)!
519 : double.infinity,
520 maxHeight: a.maxHeight.isFinite
521 ? ui.lerpDouble(a.maxHeight, b.maxHeight, t)!
522 : double.infinity,
523 );
524 }
525
526 /// Returns whether the object's constraints are normalized.
527 /// Constraints are normalized if the minimums are less than or
528 /// equal to the corresponding maximums.
529 ///
530 /// For example, a BoxConstraints object with a minWidth of 100.0
531 /// and a maxWidth of 90.0 is not normalized.
532 ///
533 /// Most of the APIs on BoxConstraints expect the constraints to be
534 /// normalized and have undefined behavior when they are not. In
535 /// debug mode, many of these APIs will assert if the constraints
536 /// are not normalized.
537 @override
538 bool get isNormalized {
539 return minWidth >= 0.0 && minWidth <= maxWidth && minHeight >= 0.0 && minHeight <= maxHeight;
540 }
541
542 @override
543 bool debugAssertIsValid({
544 bool isAppliedConstraint = false,
545 InformationCollector? informationCollector,
546 }) {
547 assert(() {
548 void throwError(DiagnosticsNode message) {
549 throw FlutterError.fromParts(<DiagnosticsNode>[
550 message,
551 if (informationCollector != null) ...informationCollector(),
552 DiagnosticsProperty<BoxConstraints>(
553 'The offending constraints were',
554 this,
555 style: DiagnosticsTreeStyle.errorProperty,
556 ),
557 ]);
558 }
559
560 if (minWidth.isNaN || maxWidth.isNaN || minHeight.isNaN || maxHeight.isNaN) {
561 final List<String> affectedFieldsList = <String>[
562 if (minWidth.isNaN) 'minWidth',
563 if (maxWidth.isNaN) 'maxWidth',
564 if (minHeight.isNaN) 'minHeight',
565 if (maxHeight.isNaN) 'maxHeight',
566 ];
567 assert(affectedFieldsList.isNotEmpty);
568 if (affectedFieldsList.length > 1) {
569 affectedFieldsList.add('and ${affectedFieldsList.removeLast()}');
570 }
571 final String whichFields = switch (affectedFieldsList.length) {
572 1 => affectedFieldsList.single,
573 2 => affectedFieldsList.join(' '),
574 _ => affectedFieldsList.join(', '),
575 };
576 throwError(
577 ErrorSummary(
578 'BoxConstraints has ${affectedFieldsList.length == 1 ? 'a NaN value' : 'NaN values'} in $whichFields.',
579 ),
580 );
581 }
582 if (minWidth < 0.0 && minHeight < 0.0) {
583 throwError(
584 ErrorSummary(
585 'BoxConstraints has both a negative minimum width and a negative minimum height.',
586 ),
587 );
588 }
589 if (minWidth < 0.0) {
590 throwError(ErrorSummary('BoxConstraints has a negative minimum width.'));
591 }
592 if (minHeight < 0.0) {
593 throwError(ErrorSummary('BoxConstraints has a negative minimum height.'));
594 }
595 if (maxWidth < minWidth && maxHeight < minHeight) {
596 throwError(
597 ErrorSummary('BoxConstraints has both width and height constraints non-normalized.'),
598 );
599 }
600 if (maxWidth < minWidth) {
601 throwError(ErrorSummary('BoxConstraints has non-normalized width constraints.'));
602 }
603 if (maxHeight < minHeight) {
604 throwError(ErrorSummary('BoxConstraints has non-normalized height constraints.'));
605 }
606 if (isAppliedConstraint) {
607 if (minWidth.isInfinite && minHeight.isInfinite) {
608 throwError(ErrorSummary('BoxConstraints forces an infinite width and infinite height.'));
609 }
610 if (minWidth.isInfinite) {
611 throwError(ErrorSummary('BoxConstraints forces an infinite width.'));
612 }
613 if (minHeight.isInfinite) {
614 throwError(ErrorSummary('BoxConstraints forces an infinite height.'));
615 }
616 }
617 assert(isNormalized);
618 return true;
619 }());
620 return isNormalized;
621 }
622
623 /// Returns a box constraints that [isNormalized].
624 ///
625 /// The returned [maxWidth] is at least as large as the [minWidth]. Similarly,
626 /// the returned [maxHeight] is at least as large as the [minHeight].
627 BoxConstraints normalize() {
628 if (isNormalized) {
629 return this;
630 }
631 final double minWidth = this.minWidth >= 0.0 ? this.minWidth : 0.0;
632 final double minHeight = this.minHeight >= 0.0 ? this.minHeight : 0.0;
633 return BoxConstraints(
634 minWidth: minWidth,
635 maxWidth: minWidth > maxWidth ? minWidth : maxWidth,
636 minHeight: minHeight,
637 maxHeight: minHeight > maxHeight ? minHeight : maxHeight,
638 );
639 }
640
641 @override
642 bool operator ==(Object other) {
643 assert(debugAssertIsValid());
644 if (identical(this, other)) {
645 return true;
646 }
647 if (other.runtimeType != runtimeType) {
648 return false;
649 }
650 assert(other is BoxConstraints && other.debugAssertIsValid());
651 return other is BoxConstraints &&
652 other.minWidth == minWidth &&
653 other.maxWidth == maxWidth &&
654 other.minHeight == minHeight &&
655 other.maxHeight == maxHeight;
656 }
657
658 @override
659 int get hashCode {
660 assert(debugAssertIsValid());
661 return Object.hash(minWidth, maxWidth, minHeight, maxHeight);
662 }
663
664 @override
665 String toString() {
666 final String annotation = isNormalized ? '' : '; NOT NORMALIZED';
667 if (minWidth == double.infinity && minHeight == double.infinity) {
668 return 'BoxConstraints(biggest$annotation)';
669 }
670 if (minWidth == 0 &&
671 maxWidth == double.infinity &&
672 minHeight == 0 &&
673 maxHeight == double.infinity) {
674 return 'BoxConstraints(unconstrained$annotation)';
675 }
676 String describe(double min, double max, String dim) {
677 if (min == max) {
678 return '$dim=${min.toStringAsFixed(1)}';
679 }
680 return '${min.toStringAsFixed(1)}<=$dim<=${max.toStringAsFixed(1)}';
681 }
682
683 final String width = describe(minWidth, maxWidth, 'w');
684 final String height = describe(minHeight, maxHeight, 'h');
685 return 'BoxConstraints($width, $height$annotation)';
686 }
687}
688
689/// Method signature for hit testing a [RenderBox].
690///
691/// Used by [BoxHitTestResult.addWithPaintTransform] to hit test children
692/// of a [RenderBox].
693///
694/// See also:
695///
696/// * [RenderBox.hitTest], which documents more details around hit testing
697/// [RenderBox]es.
698typedef BoxHitTest = bool Function(BoxHitTestResult result, Offset position);
699
700/// Method signature for hit testing a [RenderBox] with a manually
701/// managed position (one that is passed out-of-band).
702///
703/// Used by [RenderSliverSingleBoxAdapter.hitTestBoxChild] to hit test
704/// [RenderBox] children of a [RenderSliver].
705///
706/// See also:
707///
708/// * [RenderBox.hitTest], which documents more details around hit testing
709/// [RenderBox]es.
710typedef BoxHitTestWithOutOfBandPosition = bool Function(BoxHitTestResult result);
711
712/// The result of performing a hit test on [RenderBox]es.
713///
714/// An instance of this class is provided to [RenderBox.hitTest] to record the
715/// result of the hit test.
716class BoxHitTestResult extends HitTestResult {
717 /// Creates an empty hit test result for hit testing on [RenderBox].
718 BoxHitTestResult() : super();
719
720 /// Wraps `result` to create a [HitTestResult] that implements the
721 /// [BoxHitTestResult] protocol for hit testing on [RenderBox]es.
722 ///
723 /// This method is used by [RenderObject]s that adapt between the
724 /// [RenderBox]-world and the non-[RenderBox]-world to convert a (subtype of)
725 /// [HitTestResult] to a [BoxHitTestResult] for hit testing on [RenderBox]es.
726 ///
727 /// The [HitTestEntry] instances added to the returned [BoxHitTestResult] are
728 /// also added to the wrapped `result` (both share the same underlying data
729 /// structure to store [HitTestEntry] instances).
730 ///
731 /// See also:
732 ///
733 /// * [HitTestResult.wrap], which turns a [BoxHitTestResult] back into a
734 /// generic [HitTestResult].
735 /// * [SliverHitTestResult.wrap], which turns a [BoxHitTestResult] into a
736 /// [SliverHitTestResult] for hit testing on [RenderSliver] children.
737 BoxHitTestResult.wrap(super.result) : super.wrap();
738
739 /// Transforms `position` to the local coordinate system of a child for
740 /// hit-testing the child.
741 ///
742 /// The actual hit testing of the child needs to be implemented in the
743 /// provided `hitTest` callback, which is invoked with the transformed
744 /// `position` as argument.
745 ///
746 /// The provided paint `transform` (which describes the transform from the
747 /// child to the parent in 3D) is processed by
748 /// [PointerEvent.removePerspectiveTransform] to remove the
749 /// perspective component and inverted before it is used to transform
750 /// `position` from the coordinate system of the parent to the system of the
751 /// child.
752 ///
753 /// If `transform` is null it will be treated as the identity transform and
754 /// `position` is provided to the `hitTest` callback as-is. If `transform`
755 /// cannot be inverted, the `hitTest` callback is not invoked and false is
756 /// returned. Otherwise, the return value of the `hitTest` callback is
757 /// returned.
758 ///
759 /// The `position` argument may be null, which will be forwarded to the
760 /// `hitTest` callback as-is. Using null as the position can be useful if
761 /// the child speaks a different hit test protocol than the parent and the
762 /// position is not required to do the actual hit testing in that protocol.
763 ///
764 /// The function returns the return value of the `hitTest` callback.
765 ///
766 /// {@tool snippet}
767 /// This method is used in [RenderBox.hitTestChildren] when the child and
768 /// parent don't share the same origin.
769 ///
770 /// ```dart
771 /// abstract class RenderFoo extends RenderBox {
772 /// final Matrix4 _effectiveTransform = Matrix4.rotationZ(50);
773 ///
774 /// @override
775 /// void applyPaintTransform(RenderBox child, Matrix4 transform) {
776 /// transform.multiply(_effectiveTransform);
777 /// }
778 ///
779 /// @override
780 /// bool hitTestChildren(BoxHitTestResult result, { required Offset position }) {
781 /// return result.addWithPaintTransform(
782 /// transform: _effectiveTransform,
783 /// position: position,
784 /// hitTest: (BoxHitTestResult result, Offset position) {
785 /// return super.hitTestChildren(result, position: position);
786 /// },
787 /// );
788 /// }
789 /// }
790 /// ```
791 /// {@end-tool}
792 ///
793 /// See also:
794 ///
795 /// * [addWithPaintOffset], which can be used for `transform`s that are just
796 /// simple matrix translations by an [Offset].
797 /// * [addWithRawTransform], which takes a transform matrix that is directly
798 /// used to transform the position without any pre-processing.
799 bool addWithPaintTransform({
800 required Matrix4? transform,
801 required Offset position,
802 required BoxHitTest hitTest,
803 }) {
804 if (transform != null) {
805 transform = Matrix4.tryInvert(PointerEvent.removePerspectiveTransform(transform));
806 if (transform == null) {
807 // Objects are not visible on screen and cannot be hit-tested.
808 return false;
809 }
810 }
811 return addWithRawTransform(transform: transform, position: position, hitTest: hitTest);
812 }
813
814 /// Convenience method for hit testing children, that are translated by
815 /// an [Offset].
816 ///
817 /// The actual hit testing of the child needs to be implemented in the
818 /// provided `hitTest` callback, which is invoked with the transformed
819 /// `position` as argument.
820 ///
821 /// This method can be used as a convenience over [addWithPaintTransform] if
822 /// a parent paints a child at an `offset`.
823 ///
824 /// A null value for `offset` is treated as if [Offset.zero] was provided.
825 ///
826 /// The function returns the return value of the `hitTest` callback.
827 ///
828 /// See also:
829 ///
830 /// * [addWithPaintTransform], which takes a generic paint transform matrix and
831 /// documents the intended usage of this API in more detail.
832 bool addWithPaintOffset({
833 required Offset? offset,
834 required Offset position,
835 required BoxHitTest hitTest,
836 }) {
837 final Offset transformedPosition = offset == null ? position : position - offset;
838 if (offset != null) {
839 pushOffset(-offset);
840 }
841 final bool isHit = hitTest(this, transformedPosition);
842 if (offset != null) {
843 popTransform();
844 }
845 return isHit;
846 }
847
848 /// Transforms `position` to the local coordinate system of a child for
849 /// hit-testing the child.
850 ///
851 /// The actual hit testing of the child needs to be implemented in the
852 /// provided `hitTest` callback, which is invoked with the transformed
853 /// `position` as argument.
854 ///
855 /// Unlike [addWithPaintTransform], the provided `transform` matrix is used
856 /// directly to transform `position` without any pre-processing.
857 ///
858 /// If `transform` is null it will be treated as the identity transform ad
859 /// `position` is provided to the `hitTest` callback as-is.
860 ///
861 /// The function returns the return value of the `hitTest` callback.
862 ///
863 /// See also:
864 ///
865 /// * [addWithPaintTransform], which accomplishes the same thing, but takes a
866 /// _paint_ transform matrix.
867 bool addWithRawTransform({
868 required Matrix4? transform,
869 required Offset position,
870 required BoxHitTest hitTest,
871 }) {
872 final Offset transformedPosition = transform == null
873 ? position
874 : MatrixUtils.transformPoint(transform, position);
875 if (transform != null) {
876 pushTransform(transform);
877 }
878 final bool isHit = hitTest(this, transformedPosition);
879 if (transform != null) {
880 popTransform();
881 }
882 return isHit;
883 }
884
885 /// Pass-through method for adding a hit test while manually managing
886 /// the position transformation logic.
887 ///
888 /// The actual hit testing of the child needs to be implemented in the
889 /// provided `hitTest` callback. The position needs to be handled by
890 /// the caller.
891 ///
892 /// The function returns the return value of the `hitTest` callback.
893 ///
894 /// A `paintOffset`, `paintTransform`, or `rawTransform` should be
895 /// passed to the method to update the hit test stack.
896 ///
897 /// * `paintOffset` has the semantics of the `offset` passed to
898 /// [addWithPaintOffset].
899 ///
900 /// * `paintTransform` has the semantics of the `transform` passed to
901 /// [addWithPaintTransform], except that it must be invertible; it
902 /// is the responsibility of the caller to ensure this.
903 ///
904 /// * `rawTransform` has the semantics of the `transform` passed to
905 /// [addWithRawTransform].
906 ///
907 /// Exactly one of these must be non-null.
908 ///
909 /// See also:
910 ///
911 /// * [addWithPaintTransform], which takes a generic paint transform matrix and
912 /// documents the intended usage of this API in more detail.
913 bool addWithOutOfBandPosition({
914 Offset? paintOffset,
915 Matrix4? paintTransform,
916 Matrix4? rawTransform,
917 required BoxHitTestWithOutOfBandPosition hitTest,
918 }) {
919 assert(
920 (paintOffset == null && paintTransform == null && rawTransform != null) ||
921 (paintOffset == null && paintTransform != null && rawTransform == null) ||
922 (paintOffset != null && paintTransform == null && rawTransform == null),
923 'Exactly one transform or offset argument must be provided.',
924 );
925 if (paintOffset != null) {
926 pushOffset(-paintOffset);
927 } else if (rawTransform != null) {
928 pushTransform(rawTransform);
929 } else {
930 assert(paintTransform != null);
931 paintTransform = Matrix4.tryInvert(PointerEvent.removePerspectiveTransform(paintTransform!));
932 assert(paintTransform != null, 'paintTransform must be invertible.');
933 pushTransform(paintTransform!);
934 }
935 final bool isHit = hitTest(this);
936 popTransform();
937 return isHit;
938 }
939}
940
941/// A hit test entry used by [RenderBox].
942class BoxHitTestEntry extends HitTestEntry<RenderBox> {
943 /// Creates a box hit test entry.
944 BoxHitTestEntry(super.target, this.localPosition);
945
946 /// The position of the hit test in the local coordinates of [target].
947 final Offset localPosition;
948
949 @override
950 String toString() => '${describeIdentity(target)}@$localPosition';
951}
952
953/// Parent data used by [RenderBox] and its subclasses.
954///
955/// {@tool dartpad}
956/// Parent data is used to communicate to a render object about its
957/// children. In this example, there are two render objects that perform
958/// text layout. They use parent data to identify the kind of child they
959/// are laying out, and space the children accordingly.
960///
961/// ** See code in examples/api/lib/rendering/box/parent_data.0.dart **
962/// {@end-tool}
963class BoxParentData extends ParentData {
964 /// The offset at which to paint the child in the parent's coordinate system.
965 Offset offset = Offset.zero;
966
967 @override
968 String toString() => 'offset=$offset';
969}
970
971/// Abstract [ParentData] subclass for [RenderBox] subclasses that want the
972/// [ContainerRenderObjectMixin].
973///
974/// This is a convenience class that mixes in the relevant classes with
975/// the relevant type arguments.
976abstract class ContainerBoxParentData<ChildType extends RenderObject> extends BoxParentData
977 with ContainerParentDataMixin<ChildType> {}
978
979/// A wrapper that represents the baseline location of a `RenderBox`.
980extension type const BaselineOffset(double? offset) {
981 /// A value that indicates that the associated `RenderBox` does not have any
982 /// baselines.
983 ///
984 /// [BaselineOffset.noBaseline] is an identity element in most binary
985 /// operations involving two [BaselineOffset]s (such as [minOf]), for render
986 /// objects with no baselines typically do not contribute to the baseline
987 /// offset of their parents.
988 static const BaselineOffset noBaseline = BaselineOffset(null);
989
990 /// Returns a new baseline location that is `offset` pixels further away from
991 /// the origin than `this`, or unchanged if `this` is [noBaseline].
992 BaselineOffset operator +(double offset) {
993 final double? value = this.offset;
994 return BaselineOffset(value == null ? null : value + offset);
995 }
996
997 /// Compares this [BaselineOffset] and `other`, and returns whichever is closer
998 /// to the origin.
999 ///
1000 /// When both `this` and `other` are [noBaseline], this method returns
1001 /// [noBaseline]. When one of them is [noBaseline], this method returns the
1002 /// other operand that's not [noBaseline].
1003 BaselineOffset minOf(BaselineOffset other) {
1004 return switch ((this, other)) {
1005 (final double lhs?, final double rhs?) => lhs >= rhs ? other : this,
1006 (final double lhs?, null) => BaselineOffset(lhs),
1007 (null, final BaselineOffset rhs) => rhs,
1008 };
1009 }
1010}
1011
1012/// An interface that represents a memoized layout computation run by a [RenderBox].
1013///
1014/// Each subclass is inhabited by a single object. Each object represents the
1015/// signature of a memoized layout computation run by [RenderBox]. For instance,
1016/// the [dryLayout] object of the [_DryLayout] subclass represents the signature
1017/// of the [RenderBox.computeDryLayout] method: it takes a [BoxConstraints] (the
1018/// subclass's `Input` type parameter) and returns a [Size] (the subclass's
1019/// `Output` type parameter).
1020///
1021/// Subclasses do not own their own cache storage. Rather, their [memoize]
1022/// implementation takes a `cacheStorage`. If a prior computation with the same
1023/// input values has already been memoized in `cacheStorage`, it returns the
1024/// memoized value without running `computer`. Otherwise the method runs the
1025/// `computer` to compute the return value, and caches the result to
1026/// `cacheStorage`.
1027///
1028/// The layout cache storage is typically cleared in `markNeedsLayout`, but is
1029/// usually kept across [RenderObject.layout] calls because the incoming
1030/// [BoxConstraints] is always an input of every layout computation.
1031abstract class _CachedLayoutCalculation<Input extends Object, Output> {
1032 static const _DryLayout dryLayout = _DryLayout();
1033 static const _Baseline baseline = _Baseline();
1034
1035 Output memoize(_LayoutCacheStorage cacheStorage, Input input, Output Function(Input) computer);
1036
1037 // Debug information that will be used to generate the Timeline event for this type of calculation.
1038 Map<String, String> debugFillTimelineArguments(
1039 Map<String, String> timelineArguments,
1040 Input input,
1041 );
1042 String eventLabel(RenderBox renderBox);
1043}
1044
1045final class _DryLayout implements _CachedLayoutCalculation<BoxConstraints, Size> {
1046 const _DryLayout();
1047
1048 @override
1049 Size memoize(
1050 _LayoutCacheStorage cacheStorage,
1051 BoxConstraints input,
1052 Size Function(BoxConstraints) computer,
1053 ) {
1054 return (cacheStorage._cachedDryLayoutSizes ??= <BoxConstraints, Size>{}).putIfAbsent(
1055 input,
1056 () => computer(input),
1057 );
1058 }
1059
1060 @override
1061 Map<String, String> debugFillTimelineArguments(
1062 Map<String, String> timelineArguments,
1063 BoxConstraints input,
1064 ) {
1065 return timelineArguments..['getDryLayout constraints'] = '$input';
1066 }
1067
1068 @override
1069 String eventLabel(RenderBox renderBox) => '${renderBox.runtimeType}.getDryLayout';
1070}
1071
1072final class _Baseline
1073 implements _CachedLayoutCalculation<(BoxConstraints, TextBaseline), BaselineOffset> {
1074 const _Baseline();
1075
1076 @override
1077 BaselineOffset memoize(
1078 _LayoutCacheStorage cacheStorage,
1079 (BoxConstraints, TextBaseline) input,
1080 BaselineOffset Function((BoxConstraints, TextBaseline)) computer,
1081 ) {
1082 final Map<BoxConstraints, BaselineOffset> cache = switch (input.$2) {
1083 TextBaseline.alphabetic =>
1084 cacheStorage._cachedAlphabeticBaseline ??= <BoxConstraints, BaselineOffset>{},
1085 TextBaseline.ideographic =>
1086 cacheStorage._cachedIdeoBaseline ??= <BoxConstraints, BaselineOffset>{},
1087 };
1088 BaselineOffset ifAbsent() => computer(input);
1089 return cache.putIfAbsent(input.$1, ifAbsent);
1090 }
1091
1092 @override
1093 Map<String, String> debugFillTimelineArguments(
1094 Map<String, String> timelineArguments,
1095 (BoxConstraints, TextBaseline) input,
1096 ) {
1097 return timelineArguments
1098 ..['baseline type'] = '${input.$2}'
1099 ..['constraints'] = '${input.$1}';
1100 }
1101
1102 @override
1103 String eventLabel(RenderBox renderBox) => '${renderBox.runtimeType}.getDryBaseline';
1104}
1105
1106// Intrinsic dimension calculation that computes the intrinsic width given the
1107// max height, or the intrinsic height given the max width.
1108enum _IntrinsicDimension implements _CachedLayoutCalculation<double, double> {
1109 minWidth,
1110 maxWidth,
1111 minHeight,
1112 maxHeight;
1113
1114 @override
1115 double memoize(_LayoutCacheStorage cacheStorage, double input, double Function(double) computer) {
1116 return (cacheStorage._cachedIntrinsicDimensions ??= <(_IntrinsicDimension, double), double>{})
1117 .putIfAbsent((this, input), () => computer(input));
1118 }
1119
1120 @override
1121 Map<String, String> debugFillTimelineArguments(
1122 Map<String, String> timelineArguments,
1123 double input,
1124 ) {
1125 return timelineArguments
1126 ..['intrinsics dimension'] = name
1127 ..['intrinsics argument'] = '$input';
1128 }
1129
1130 @override
1131 String eventLabel(RenderBox renderBox) => '${renderBox.runtimeType} intrinsics';
1132}
1133
1134final class _LayoutCacheStorage {
1135 Map<(_IntrinsicDimension, double), double>? _cachedIntrinsicDimensions;
1136 Map<BoxConstraints, Size>? _cachedDryLayoutSizes;
1137 Map<BoxConstraints, BaselineOffset>? _cachedAlphabeticBaseline;
1138 Map<BoxConstraints, BaselineOffset>? _cachedIdeoBaseline;
1139
1140 // Returns a boolean indicating whether the cache storage has cached
1141 // intrinsics / dry layout data in it.
1142 bool clear() {
1143 final bool hasCache =
1144 (_cachedDryLayoutSizes?.isNotEmpty ?? false) ||
1145 (_cachedIntrinsicDimensions?.isNotEmpty ?? false) ||
1146 (_cachedAlphabeticBaseline?.isNotEmpty ?? false) ||
1147 (_cachedIdeoBaseline?.isNotEmpty ?? false);
1148
1149 if (hasCache) {
1150 _cachedDryLayoutSizes?.clear();
1151 _cachedIntrinsicDimensions?.clear();
1152 _cachedAlphabeticBaseline?.clear();
1153 _cachedIdeoBaseline?.clear();
1154 }
1155 return hasCache;
1156 }
1157}
1158
1159/// A render object in a 2D Cartesian coordinate system.
1160///
1161/// The [size] of each box is expressed as a width and a height. Each box has
1162/// its own coordinate system in which its upper left corner is placed at (0,
1163/// 0). The lower right corner of the box is therefore at (width, height). The
1164/// box contains all the points including the upper left corner and extending
1165/// to, but not including, the lower right corner.
1166///
1167/// Box layout is performed by passing a [BoxConstraints] object down the tree.
1168/// The box constraints establish a min and max value for the child's width and
1169/// height. In determining its size, the child must respect the constraints
1170/// given to it by its parent.
1171///
1172/// This protocol is sufficient for expressing a number of common box layout
1173/// data flows. For example, to implement a width-in-height-out data flow, call
1174/// your child's [layout] function with a set of box constraints with a tight
1175/// width value (and pass true for parentUsesSize). After the child determines
1176/// its height, use the child's height to determine your size.
1177///
1178/// ## Writing a RenderBox subclass
1179///
1180/// One would implement a new [RenderBox] subclass to describe a new layout
1181/// model, new paint model, new hit-testing model, or new semantics model, while
1182/// remaining in the Cartesian space defined by the [RenderBox] protocol.
1183///
1184/// To create a new protocol, consider subclassing [RenderObject] instead.
1185///
1186/// ### Constructors and properties of a new RenderBox subclass
1187///
1188/// The constructor will typically take a named argument for each property of
1189/// the class. The value is then passed to a private field of the class and the
1190/// constructor asserts its correctness (e.g. if it should not be null, it
1191/// asserts it's not null).
1192///
1193/// Properties have the form of a getter/setter/field group like the following:
1194///
1195/// ```dart
1196/// AxisDirection get axis => _axis;
1197/// AxisDirection _axis = AxisDirection.down; // or initialized in constructor
1198/// set axis(AxisDirection value) {
1199/// if (value == _axis) {
1200/// return;
1201/// }
1202/// _axis = value;
1203/// markNeedsLayout();
1204/// }
1205/// ```
1206///
1207/// The setter will typically finish with either a call to [markNeedsLayout], if
1208/// the layout uses this property, or [markNeedsPaint], if only the painter
1209/// function does. (No need to call both, [markNeedsLayout] implies
1210/// [markNeedsPaint].)
1211///
1212/// Consider layout and paint to be expensive; be conservative about calling
1213/// [markNeedsLayout] or [markNeedsPaint]. They should only be called if the
1214/// layout (or paint, respectively) has actually changed.
1215///
1216/// ### Children
1217///
1218/// If a render object is a leaf, that is, it cannot have any children, then
1219/// ignore this section. (Examples of leaf render objects are [RenderImage] and
1220/// [RenderParagraph].)
1221///
1222/// For render objects with children, there are four possible scenarios:
1223///
1224/// * A single [RenderBox] child. In this scenario, consider inheriting from
1225/// [RenderProxyBox] (if the render object sizes itself to match the child) or
1226/// [RenderShiftedBox] (if the child will be smaller than the box and the box
1227/// will align the child inside itself).
1228///
1229/// * A single child, but it isn't a [RenderBox]. Use the
1230/// [RenderObjectWithChildMixin] mixin.
1231///
1232/// * A single list of children. Use the [ContainerRenderObjectMixin] mixin.
1233///
1234/// * A more complicated child model.
1235///
1236/// #### Using RenderProxyBox
1237///
1238/// By default, a [RenderProxyBox] render object sizes itself to fit its child, or
1239/// to be as small as possible if there is no child; it passes all hit testing
1240/// and painting on to the child, and intrinsic dimensions and baseline
1241/// measurements similarly are proxied to the child.
1242///
1243/// A subclass of [RenderProxyBox] just needs to override the parts of the
1244/// [RenderBox] protocol that matter. For example, [RenderOpacity] just
1245/// overrides the paint method (and [alwaysNeedsCompositing] to reflect what the
1246/// paint method does, and the [visitChildrenForSemantics] method so that the
1247/// child is hidden from accessibility tools when it's invisible), and adds an
1248/// [RenderOpacity.opacity] field.
1249///
1250/// [RenderProxyBox] assumes that the child is the size of the parent and
1251/// positioned at 0,0. If this is not true, then use [RenderShiftedBox] instead.
1252///
1253/// See
1254/// [proxy_box.dart](https://github.com/flutter/flutter/blob/main/packages/flutter/lib/src/rendering/proxy_box.dart)
1255/// for examples of inheriting from [RenderProxyBox].
1256///
1257/// #### Using RenderShiftedBox
1258///
1259/// By default, a [RenderShiftedBox] acts much like a [RenderProxyBox] but
1260/// without assuming that the child is positioned at 0,0 (the actual position
1261/// recorded in the child's [parentData] field is used), and without providing a
1262/// default layout algorithm.
1263///
1264/// See
1265/// [shifted_box.dart](https://github.com/flutter/flutter/blob/main/packages/flutter/lib/src/rendering/shifted_box.dart)
1266/// for examples of inheriting from [RenderShiftedBox].
1267///
1268/// #### Kinds of children and child-specific data
1269///
1270/// A [RenderBox] doesn't have to have [RenderBox] children. One can use another
1271/// subclass of [RenderObject] for a [RenderBox]'s children. See the discussion
1272/// at [RenderObject].
1273///
1274/// Children can have additional data owned by the parent but stored on the
1275/// child using the [parentData] field. The class used for that data must
1276/// inherit from [ParentData]. The [setupParentData] method is used to
1277/// initialize the [parentData] field of a child when the child is attached.
1278///
1279/// By convention, [RenderBox] objects that have [RenderBox] children use the
1280/// [BoxParentData] class, which has a [BoxParentData.offset] field to store the
1281/// position of the child relative to the parent. ([RenderProxyBox] does not
1282/// need this offset and therefore is an exception to this rule.)
1283///
1284/// #### Using RenderObjectWithChildMixin
1285///
1286/// If a render object has a single child but it isn't a [RenderBox], then the
1287/// [RenderObjectWithChildMixin] class, which is a mixin that will handle the
1288/// boilerplate of managing a child, will be useful.
1289///
1290/// It's a generic class with one type argument, the type of the child. For
1291/// example, if you are building a `RenderFoo` class which takes a single
1292/// `RenderBar` child, you would use the mixin as follows:
1293///
1294/// ```dart
1295/// class RenderFoo extends RenderBox
1296/// with RenderObjectWithChildMixin<RenderBar> {
1297/// // ...
1298/// }
1299/// ```
1300///
1301/// Since the `RenderFoo` class itself is still a [RenderBox] in this case, you
1302/// still have to implement the [RenderBox] layout algorithm, as well as
1303/// features like intrinsics and baselines, painting, and hit testing.
1304///
1305/// #### Using ContainerRenderObjectMixin
1306///
1307/// If a render box can have multiple children, then the
1308/// [ContainerRenderObjectMixin] mixin can be used to handle the boilerplate. It
1309/// uses a linked list to model the children in a manner that is easy to mutate
1310/// dynamically and that can be walked efficiently. Random access is not
1311/// efficient in this model; if you need random access to the children consider
1312/// the next section on more complicated child models.
1313///
1314/// The [ContainerRenderObjectMixin] class has two type arguments. The first is
1315/// the type of the child objects. The second is the type for their
1316/// [parentData]. The class used for [parentData] must itself have the
1317/// [ContainerParentDataMixin] class mixed into it; this is where
1318/// [ContainerRenderObjectMixin] stores the linked list. A [ParentData] class
1319/// can extend [ContainerBoxParentData]; this is essentially
1320/// [BoxParentData] mixed with [ContainerParentDataMixin]. For example, if a
1321/// `RenderFoo` class wanted to have a linked list of [RenderBox] children, one
1322/// might create a `FooParentData` class as follows:
1323///
1324/// ```dart
1325/// class FooParentData extends ContainerBoxParentData<RenderBox> {
1326/// // (any fields you might need for these children)
1327/// }
1328/// ```
1329///
1330/// When using [ContainerRenderObjectMixin] in a [RenderBox], consider mixing in
1331/// [RenderBoxContainerDefaultsMixin], which provides a collection of utility
1332/// methods that implement common parts of the [RenderBox] protocol (such as
1333/// painting the children).
1334///
1335/// The declaration of the `RenderFoo` class itself would thus look like this:
1336///
1337/// ```dart
1338/// // continuing from previous example...
1339/// class RenderFoo extends RenderBox with
1340/// ContainerRenderObjectMixin<RenderBox, FooParentData>,
1341/// RenderBoxContainerDefaultsMixin<RenderBox, FooParentData> {
1342/// // ...
1343/// }
1344/// ```
1345///
1346/// When walking the children (e.g. during layout), the following pattern is
1347/// commonly used (in this case assuming that the children are all [RenderBox]
1348/// objects and that this render object uses `FooParentData` objects for its
1349/// children's [parentData] fields):
1350///
1351/// ```dart
1352/// // continuing from previous example...
1353/// RenderBox? child = firstChild;
1354/// while (child != null) {
1355/// final FooParentData childParentData = child.parentData! as FooParentData;
1356/// // ...operate on child and childParentData...
1357/// assert(child.parentData == childParentData);
1358/// child = childParentData.nextSibling;
1359/// }
1360/// ```
1361///
1362/// #### More complicated child models
1363///
1364/// Render objects can have more complicated models, for example a map of
1365/// children keyed on an enum, or a 2D grid of efficiently randomly-accessible
1366/// children, or multiple lists of children, etc. If a render object has a model
1367/// that can't be handled by the mixins above, it must implement the
1368/// [RenderObject] child protocol, as follows:
1369///
1370/// * Any time a child is removed, call [dropChild] with the child.
1371///
1372/// * Any time a child is added, call [adoptChild] with the child.
1373///
1374/// * Implement the [attach] method such that it calls [attach] on each child.
1375///
1376/// * Implement the [detach] method such that it calls [detach] on each child.
1377///
1378/// * Implement the [redepthChildren] method such that it calls [redepthChild]
1379/// on each child.
1380///
1381/// * Implement the [visitChildren] method such that it calls its argument for
1382/// each child, typically in paint order (back-most to front-most).
1383///
1384/// * Implement [debugDescribeChildren] such that it outputs a [DiagnosticsNode]
1385/// for each child.
1386///
1387/// Implementing these seven bullet points is essentially all that the two
1388/// aforementioned mixins do.
1389///
1390/// ### Layout
1391///
1392/// [RenderBox] classes implement a layout algorithm. They have a set of
1393/// constraints provided to them, and they size themselves based on those
1394/// constraints and whatever other inputs they may have (for example, their
1395/// children or properties).
1396///
1397/// When implementing a [RenderBox] subclass, one must make a choice. Does it
1398/// size itself exclusively based on the constraints, or does it use any other
1399/// information in sizing itself? An example of sizing purely based on the
1400/// constraints would be growing to fit the parent.
1401///
1402/// Sizing purely based on the constraints allows the system to make some
1403/// significant optimizations. Classes that use this approach should override
1404/// [sizedByParent] to return true, and then override [computeDryLayout] to
1405/// compute the [Size] using nothing but the constraints, e.g.:
1406///
1407/// ```dart
1408/// @override
1409/// bool get sizedByParent => true;
1410///
1411/// @override
1412/// Size computeDryLayout(BoxConstraints constraints) {
1413/// return constraints.smallest;
1414/// }
1415/// ```
1416///
1417/// Otherwise, the size is set in the [performLayout] function.
1418///
1419/// The [performLayout] function is where render boxes decide, if they are not
1420/// [sizedByParent], what [size] they should be, and also where they decide
1421/// where their children should be.
1422///
1423/// #### Layout of RenderBox children
1424///
1425/// The [performLayout] function should call the [layout] function of each (box)
1426/// child, passing it a [BoxConstraints] object describing the constraints
1427/// within which the child can render. Passing tight constraints (see
1428/// [BoxConstraints.isTight]) to the child will allow the rendering library to
1429/// apply some optimizations, as it knows that if the constraints are tight, the
1430/// child's dimensions cannot change even if the layout of the child itself
1431/// changes.
1432///
1433/// If the [performLayout] function will use the child's size to affect other
1434/// aspects of the layout, for example if the render box sizes itself around the
1435/// child, or positions several children based on the size of those children,
1436/// then it must specify the `parentUsesSize` argument to the child's [layout]
1437/// function, setting it to true.
1438///
1439/// This flag turns off some optimizations; algorithms that do not rely on the
1440/// children's sizes will be more efficient. (In particular, relying on the
1441/// child's [size] means that if the child is marked dirty for layout, the
1442/// parent will probably also be marked dirty for layout, unless the
1443/// [constraints] given by the parent to the child were tight constraints.)
1444///
1445/// For [RenderBox] classes that do not inherit from [RenderProxyBox], once they
1446/// have laid out their children, they should also position them, by setting the
1447/// [BoxParentData.offset] field of each child's [parentData] object.
1448///
1449/// #### Layout of non-RenderBox children
1450///
1451/// The children of a [RenderBox] do not have to be [RenderBox]es themselves. If
1452/// they use another protocol (as discussed at [RenderObject]), then instead of
1453/// [BoxConstraints], the parent would pass in the appropriate [Constraints]
1454/// subclass, and instead of reading the child's size, the parent would read
1455/// whatever the output of [layout] is for that layout protocol. The
1456/// `parentUsesSize` flag is still used to indicate whether the parent is going
1457/// to read that output, and optimizations still kick in if the child has tight
1458/// constraints (as defined by [Constraints.isTight]).
1459///
1460/// ### Painting
1461///
1462/// To describe how a render box paints, implement the [paint] method. It is
1463/// given a [PaintingContext] object and an [Offset]. The painting context
1464/// provides methods to affect the layer tree as well as a
1465/// [PaintingContext.canvas] which can be used to add drawing commands. The
1466/// canvas object should not be cached across calls to the [PaintingContext]'s
1467/// methods; every time a method on [PaintingContext] is called, there is a
1468/// chance that the canvas will change identity. The offset specifies the
1469/// position of the top left corner of the box in the coordinate system of the
1470/// [PaintingContext.canvas].
1471///
1472/// To draw text on a canvas, use a [TextPainter].
1473///
1474/// To draw an image to a canvas, use the [paintImage] method.
1475///
1476/// A [RenderBox] that uses methods on [PaintingContext] that introduce new
1477/// layers should override the [alwaysNeedsCompositing] getter and set it to
1478/// true. If the object sometimes does and sometimes does not, it can have that
1479/// getter return true in some cases and false in others. In that case, whenever
1480/// the return value would change, call [markNeedsCompositingBitsUpdate]. (This
1481/// is done automatically when a child is added or removed, so you don't have to
1482/// call it explicitly if the [alwaysNeedsCompositing] getter only changes value
1483/// based on the presence or absence of children.)
1484///
1485/// Anytime anything changes on the object that would cause the [paint] method
1486/// to paint something different (but would not cause the layout to change),
1487/// the object should call [markNeedsPaint].
1488///
1489/// #### Painting children
1490///
1491/// The [paint] method's `context` argument has a [PaintingContext.paintChild]
1492/// method, which should be called for each child that is to be painted. It
1493/// should be given a reference to the child, and an [Offset] giving the
1494/// position of the child relative to the parent.
1495///
1496/// If the [paint] method applies a transform to the painting context before
1497/// painting children (or generally applies an additional offset beyond the
1498/// offset it was itself given as an argument), then the [applyPaintTransform]
1499/// method should also be overridden. That method must adjust the matrix that it
1500/// is given in the same manner as it transformed the painting context and
1501/// offset before painting the given child. This is used by the [globalToLocal]
1502/// and [localToGlobal] methods.
1503///
1504/// #### Hit Tests
1505///
1506/// Hit testing for render boxes is implemented by the [hitTest] method. The
1507/// default implementation of this method defers to [hitTestSelf] and
1508/// [hitTestChildren]. When implementing hit testing, you can either override
1509/// these latter two methods, or ignore them and just override [hitTest].
1510///
1511/// The [hitTest] method itself is given an [Offset], and must return true if the
1512/// object or one of its children has absorbed the hit (preventing objects below
1513/// this one from being hit), or false if the hit can continue to other objects
1514/// below this one.
1515///
1516/// For each child [RenderBox], the [hitTest] method on the child should be
1517/// called with the same [HitTestResult] argument and with the point transformed
1518/// into the child's coordinate space (in the same manner that the
1519/// [applyPaintTransform] method would). The default implementation defers to
1520/// [hitTestChildren] to call the children. [RenderBoxContainerDefaultsMixin]
1521/// provides a [RenderBoxContainerDefaultsMixin.defaultHitTestChildren] method
1522/// that does this assuming that the children are axis-aligned, not transformed,
1523/// and positioned according to the [BoxParentData.offset] field of the
1524/// [parentData]; more elaborate boxes can override [hitTestChildren]
1525/// accordingly.
1526///
1527/// If the object is hit, then it should also add itself to the [HitTestResult]
1528/// object that is given as an argument to the [hitTest] method, using
1529/// [HitTestResult.add]. The default implementation defers to [hitTestSelf] to
1530/// determine if the box is hit. If the object adds itself before the children
1531/// can add themselves, then it will be as if the object was above the children.
1532/// If it adds itself after the children, then it will be as if it was below the
1533/// children. Entries added to the [HitTestResult] object should use the
1534/// [BoxHitTestEntry] class. The entries are subsequently walked by the system
1535/// in the order they were added, and for each entry, the target's [handleEvent]
1536/// method is called, passing in the [HitTestEntry] object.
1537///
1538/// Hit testing cannot rely on painting having happened.
1539///
1540/// ### Semantics
1541///
1542/// For a render box to be accessible, implement the
1543/// [describeApproximatePaintClip], [visitChildrenForSemantics], and
1544/// [describeSemanticsConfiguration] methods. The default implementations are
1545/// sufficient for objects that only affect layout, but nodes that represent
1546/// interactive components or information (diagrams, text, images, etc) should
1547/// provide more complete implementations. For more information, see the
1548/// documentation for these members.
1549///
1550/// ### Intrinsics and Baselines
1551///
1552/// The layout, painting, hit testing, and semantics protocols are common to all
1553/// render objects. [RenderBox] objects must implement two additional protocols:
1554/// intrinsic sizing and baseline measurements.
1555///
1556/// There are four methods to implement for intrinsic sizing, to compute the
1557/// minimum and maximum intrinsic width and height of the box. The documentation
1558/// for these methods discusses the protocol in detail:
1559/// [computeMinIntrinsicWidth], [computeMaxIntrinsicWidth],
1560/// [computeMinIntrinsicHeight], [computeMaxIntrinsicHeight].
1561///
1562/// Be sure to set [debugCheckIntrinsicSizes] to true in your unit tests if you
1563/// do override any of these methods, which will add additional checks to
1564/// help validate your implementation.
1565///
1566/// In addition, if the box has any children, it must implement
1567/// [computeDistanceToActualBaseline]. [RenderProxyBox] provides a simple
1568/// implementation that forwards to the child; [RenderShiftedBox] provides an
1569/// implementation that offsets the child's baseline information by the position
1570/// of the child relative to the parent. If you do not inherited from either of
1571/// these classes, however, you must implement the algorithm yourself.
1572abstract class RenderBox extends RenderObject {
1573 @override
1574 void setupParentData(covariant RenderObject child) {
1575 if (child.parentData is! BoxParentData) {
1576 child.parentData = BoxParentData();
1577 }
1578 }
1579
1580 final _LayoutCacheStorage _layoutCacheStorage = _LayoutCacheStorage();
1581
1582 static int _debugIntrinsicsDepth = 0;
1583 Output _computeIntrinsics<Input extends Object, Output>(
1584 _CachedLayoutCalculation<Input, Output> type,
1585 Input input,
1586 Output Function(Input) computer,
1587 ) {
1588 assert(
1589 RenderObject.debugCheckingIntrinsics || !debugDoingThisResize,
1590 ); // performResize should not depend on anything except the incoming constraints
1591 bool shouldCache = true;
1592 assert(() {
1593 // we don't want the debug-mode intrinsic tests to affect
1594 // who gets marked dirty, etc.
1595 shouldCache = !RenderObject.debugCheckingIntrinsics;
1596 return true;
1597 }());
1598 return shouldCache ? _computeWithTimeline(type, input, computer) : computer(input);
1599 }
1600
1601 Output _computeWithTimeline<Input extends Object, Output>(
1602 _CachedLayoutCalculation<Input, Output> type,
1603 Input input,
1604 Output Function(Input) computer,
1605 ) {
1606 Map<String, String>? debugTimelineArguments;
1607 assert(() {
1608 final Map<String, String> arguments = debugEnhanceLayoutTimelineArguments
1609 ? toDiagnosticsNode().toTimelineArguments()!
1610 : <String, String>{};
1611 debugTimelineArguments = type.debugFillTimelineArguments(arguments, input);
1612 return true;
1613 }());
1614 if (!kReleaseMode) {
1615 if (debugProfileLayoutsEnabled || _debugIntrinsicsDepth == 0) {
1616 FlutterTimeline.startSync(type.eventLabel(this), arguments: debugTimelineArguments);
1617 }
1618 _debugIntrinsicsDepth += 1;
1619 }
1620 final Output result = type.memoize(_layoutCacheStorage, input, computer);
1621 if (!kReleaseMode) {
1622 _debugIntrinsicsDepth -= 1;
1623 if (debugProfileLayoutsEnabled || _debugIntrinsicsDepth == 0) {
1624 FlutterTimeline.finishSync();
1625 }
1626 }
1627 return result;
1628 }
1629
1630 /// Returns the minimum width that this box could be without failing to
1631 /// correctly paint its contents within itself, without clipping.
1632 ///
1633 /// The height argument may give a specific height to assume. The given height
1634 /// can be infinite, meaning that the intrinsic width in an unconstrained
1635 /// environment is being requested. The given height should never be negative
1636 /// or null.
1637 ///
1638 /// This function should only be called on one's children. Calling this
1639 /// function couples the child with the parent so that when the child's layout
1640 /// changes, the parent is notified (via [markNeedsLayout]).
1641 ///
1642 /// Calling this function is expensive as it can result in O(N^2) behavior.
1643 ///
1644 /// Do not override this method. Instead, implement [computeMinIntrinsicWidth].
1645 @mustCallSuper
1646 double getMinIntrinsicWidth(double height) {
1647 assert(() {
1648 if (height < 0.0) {
1649 throw FlutterError.fromParts(<DiagnosticsNode>[
1650 ErrorSummary('The height argument to getMinIntrinsicWidth was negative.'),
1651 ErrorDescription('The argument to getMinIntrinsicWidth must not be negative or null.'),
1652 ErrorHint(
1653 'If you perform computations on another height before passing it to '
1654 'getMinIntrinsicWidth, consider using math.max() or double.clamp() '
1655 'to force the value into the valid range.',
1656 ),
1657 ]);
1658 }
1659 return true;
1660 }());
1661 return _computeIntrinsics(_IntrinsicDimension.minWidth, height, computeMinIntrinsicWidth);
1662 }
1663
1664 /// Computes the value returned by [getMinIntrinsicWidth]. Do not call this
1665 /// function directly, instead, call [getMinIntrinsicWidth].
1666 ///
1667 /// Override in subclasses that implement [performLayout]. This method should
1668 /// return the minimum width that this box could be without failing to
1669 /// correctly paint its contents within itself, without clipping.
1670 ///
1671 /// If the layout algorithm is independent of the context (e.g. it always
1672 /// tries to be a particular size), or if the layout algorithm is
1673 /// width-in-height-out, or if the layout algorithm uses both the incoming
1674 /// width and height constraints (e.g. it always sizes itself to
1675 /// [BoxConstraints.biggest]), then the `height` argument should be ignored.
1676 ///
1677 /// If the layout algorithm is strictly height-in-width-out, or is
1678 /// height-in-width-out when the width is unconstrained, then the height
1679 /// argument is the height to use.
1680 ///
1681 /// The `height` argument will never be negative or null. It may be infinite.
1682 ///
1683 /// If this algorithm depends on the intrinsic dimensions of a child, the
1684 /// intrinsic dimensions of that child should be obtained using the functions
1685 /// whose names start with `get`, not `compute`.
1686 ///
1687 /// This function should never return a negative or infinite value.
1688 ///
1689 /// Be sure to set [debugCheckIntrinsicSizes] to true in your unit tests if
1690 /// you do override this method, which will add additional checks to help
1691 /// validate your implementation.
1692 ///
1693 /// ## Examples
1694 ///
1695 /// ### Text
1696 ///
1697 /// English text is the canonical example of a width-in-height-out algorithm.
1698 /// The `height` argument is therefore ignored.
1699 ///
1700 /// Consider the string "Hello World". The _maximum_ intrinsic width (as
1701 /// returned from [computeMaxIntrinsicWidth]) would be the width of the string
1702 /// with no line breaks.
1703 ///
1704 /// The minimum intrinsic width would be the width of the widest word, "Hello"
1705 /// or "World". If the text is rendered in an even narrower width, however, it
1706 /// might still not overflow. For example, maybe the rendering would put a
1707 /// line-break half-way through the words, as in "Hel⁞lo⁞Wor⁞ld". However,
1708 /// this wouldn't be a _correct_ rendering, and [computeMinIntrinsicWidth] is
1709 /// defined as returning the minimum width that the box could be without
1710 /// failing to _correctly_ paint the contents within itself.
1711 ///
1712 /// The minimum intrinsic _height_ for a given width _smaller_ than the
1713 /// minimum intrinsic width could therefore be greater than the minimum
1714 /// intrinsic height for the minimum intrinsic width.
1715 ///
1716 /// ### Viewports (e.g. scrolling lists)
1717 ///
1718 /// Some render boxes are intended to clip their children. For example, the
1719 /// render box for a scrolling list might always size itself to its parents'
1720 /// size (or rather, to the maximum incoming constraints), regardless of the
1721 /// children's sizes, and then clip the children and position them based on
1722 /// the current scroll offset.
1723 ///
1724 /// The intrinsic dimensions in these cases still depend on the children, even
1725 /// though the layout algorithm sizes the box in a way independent of the
1726 /// children. It is the size that is needed to paint the box's contents (in
1727 /// this case, the children) _without clipping_ that matters.
1728 ///
1729 /// ### When the intrinsic dimensions cannot be known
1730 ///
1731 /// There are cases where render objects do not have an efficient way to
1732 /// compute their intrinsic dimensions. For example, it may be prohibitively
1733 /// expensive to reify and measure every child of a lazy viewport (viewports
1734 /// generally only instantiate the actually visible children), or the
1735 /// dimensions may be computed by a callback about which the render object
1736 /// cannot reason.
1737 ///
1738 /// In such cases, it may be impossible (or at least impractical) to actually
1739 /// return a valid answer. In such cases, the intrinsic functions should throw
1740 /// when [RenderObject.debugCheckingIntrinsics] is false and asserts are
1741 /// enabled, and return 0.0 otherwise.
1742 ///
1743 /// See the implementations of [LayoutBuilder] or [RenderViewportBase] for
1744 /// examples (in particular,
1745 /// [RenderViewportBase.debugThrowIfNotCheckingIntrinsics]).
1746 ///
1747 /// ### Aspect-ratio-driven boxes
1748 ///
1749 /// Some boxes always return a fixed size based on the constraints. For these
1750 /// boxes, the intrinsic functions should return the appropriate size when the
1751 /// incoming `height` or `width` argument is finite, treating that as a tight
1752 /// constraint in the respective direction and treating the other direction's
1753 /// constraints as unbounded. This is because the definitions of
1754 /// [computeMinIntrinsicWidth] and [computeMinIntrinsicHeight] are in terms of
1755 /// what the dimensions _could be_, and such boxes can only be one size in
1756 /// such cases.
1757 ///
1758 /// When the incoming argument is not finite, then they should return the
1759 /// actual intrinsic dimensions based on the contents, as any other box would.
1760 ///
1761 /// See also:
1762 ///
1763 /// * [computeMaxIntrinsicWidth], which computes the smallest width beyond
1764 /// which increasing the width never decreases the preferred height.
1765 @protected
1766 double computeMinIntrinsicWidth(double height) {
1767 return 0.0;
1768 }
1769
1770 /// Returns the smallest width beyond which increasing the width never
1771 /// decreases the preferred height. The preferred height is the value that
1772 /// would be returned by [getMinIntrinsicHeight] for that width.
1773 ///
1774 /// The height argument may give a specific height to assume. The given height
1775 /// can be infinite, meaning that the intrinsic width in an unconstrained
1776 /// environment is being requested. The given height should never be negative
1777 /// or null.
1778 ///
1779 /// This function should only be called on one's children. Calling this
1780 /// function couples the child with the parent so that when the child's layout
1781 /// changes, the parent is notified (via [markNeedsLayout]).
1782 ///
1783 /// Calling this function is expensive as it can result in O(N^2) behavior.
1784 ///
1785 /// Do not override this method. Instead, implement
1786 /// [computeMaxIntrinsicWidth].
1787 @mustCallSuper
1788 double getMaxIntrinsicWidth(double height) {
1789 assert(() {
1790 if (height < 0.0) {
1791 throw FlutterError.fromParts(<DiagnosticsNode>[
1792 ErrorSummary('The height argument to getMaxIntrinsicWidth was negative.'),
1793 ErrorDescription('The argument to getMaxIntrinsicWidth must not be negative or null.'),
1794 ErrorHint(
1795 'If you perform computations on another height before passing it to '
1796 'getMaxIntrinsicWidth, consider using math.max() or double.clamp() '
1797 'to force the value into the valid range.',
1798 ),
1799 ]);
1800 }
1801 return true;
1802 }());
1803 return _computeIntrinsics(_IntrinsicDimension.maxWidth, height, computeMaxIntrinsicWidth);
1804 }
1805
1806 /// Computes the value returned by [getMaxIntrinsicWidth]. Do not call this
1807 /// function directly, instead, call [getMaxIntrinsicWidth].
1808 ///
1809 /// Override in subclasses that implement [performLayout]. This should return
1810 /// the smallest width beyond which increasing the width never decreases the
1811 /// preferred height. The preferred height is the value that would be returned
1812 /// by [computeMinIntrinsicHeight] for that width.
1813 ///
1814 /// If the layout algorithm is strictly height-in-width-out, or is
1815 /// height-in-width-out when the width is unconstrained, then this should
1816 /// return the same value as [computeMinIntrinsicWidth] for the same height.
1817 ///
1818 /// Otherwise, the height argument should be ignored, and the returned value
1819 /// should be equal to or bigger than the value returned by
1820 /// [computeMinIntrinsicWidth].
1821 ///
1822 /// The `height` argument will never be negative or null. It may be infinite.
1823 ///
1824 /// The value returned by this method might not match the size that the object
1825 /// would actually take. For example, a [RenderBox] subclass that always
1826 /// exactly sizes itself using [BoxConstraints.biggest] might well size itself
1827 /// bigger than its max intrinsic size.
1828 ///
1829 /// If this algorithm depends on the intrinsic dimensions of a child, the
1830 /// intrinsic dimensions of that child should be obtained using the functions
1831 /// whose names start with `get`, not `compute`.
1832 ///
1833 /// This function should never return a negative or infinite value.
1834 ///
1835 /// Be sure to set [debugCheckIntrinsicSizes] to true in your unit tests if
1836 /// you do override this method, which will add additional checks to help
1837 /// validate your implementation.
1838 ///
1839 /// See also:
1840 ///
1841 /// * [computeMinIntrinsicWidth], which has usage examples.
1842 @visibleForOverriding
1843 @protected
1844 double computeMaxIntrinsicWidth(double height) {
1845 return 0.0;
1846 }
1847
1848 /// Returns the minimum height that this box could be without failing to
1849 /// correctly paint its contents within itself, without clipping.
1850 ///
1851 /// The width argument may give a specific width to assume. The given width
1852 /// can be infinite, meaning that the intrinsic height in an unconstrained
1853 /// environment is being requested. The given width should never be negative
1854 /// or null.
1855 ///
1856 /// This function should only be called on one's children. Calling this
1857 /// function couples the child with the parent so that when the child's layout
1858 /// changes, the parent is notified (via [markNeedsLayout]).
1859 ///
1860 /// Calling this function is expensive as it can result in O(N^2) behavior.
1861 ///
1862 /// Do not override this method. Instead, implement
1863 /// [computeMinIntrinsicHeight].
1864 @mustCallSuper
1865 double getMinIntrinsicHeight(double width) {
1866 assert(() {
1867 if (width < 0.0) {
1868 throw FlutterError.fromParts(<DiagnosticsNode>[
1869 ErrorSummary('The width argument to getMinIntrinsicHeight was negative.'),
1870 ErrorDescription('The argument to getMinIntrinsicHeight must not be negative or null.'),
1871 ErrorHint(
1872 'If you perform computations on another width before passing it to '
1873 'getMinIntrinsicHeight, consider using math.max() or double.clamp() '
1874 'to force the value into the valid range.',
1875 ),
1876 ]);
1877 }
1878 return true;
1879 }());
1880 return _computeIntrinsics(_IntrinsicDimension.minHeight, width, computeMinIntrinsicHeight);
1881 }
1882
1883 /// Computes the value returned by [getMinIntrinsicHeight]. Do not call this
1884 /// function directly, instead, call [getMinIntrinsicHeight].
1885 ///
1886 /// Override in subclasses that implement [performLayout]. Should return the
1887 /// minimum height that this box could be without failing to correctly paint
1888 /// its contents within itself, without clipping.
1889 ///
1890 /// If the layout algorithm is independent of the context (e.g. it always
1891 /// tries to be a particular size), or if the layout algorithm is
1892 /// height-in-width-out, or if the layout algorithm uses both the incoming
1893 /// height and width constraints (e.g. it always sizes itself to
1894 /// [BoxConstraints.biggest]), then the `width` argument should be ignored.
1895 ///
1896 /// If the layout algorithm is strictly width-in-height-out, or is
1897 /// width-in-height-out when the height is unconstrained, then the width
1898 /// argument is the width to use.
1899 ///
1900 /// The `width` argument will never be negative or null. It may be infinite.
1901 ///
1902 /// If this algorithm depends on the intrinsic dimensions of a child, the
1903 /// intrinsic dimensions of that child should be obtained using the functions
1904 /// whose names start with `get`, not `compute`.
1905 ///
1906 /// This function should never return a negative or infinite value.
1907 ///
1908 /// Be sure to set [debugCheckIntrinsicSizes] to true in your unit tests if
1909 /// you do override this method, which will add additional checks to help
1910 /// validate your implementation.
1911 ///
1912 /// See also:
1913 ///
1914 /// * [computeMinIntrinsicWidth], which has usage examples.
1915 /// * [computeMaxIntrinsicHeight], which computes the smallest height beyond
1916 /// which increasing the height never decreases the preferred width.
1917 @visibleForOverriding
1918 @protected
1919 double computeMinIntrinsicHeight(double width) {
1920 return 0.0;
1921 }
1922
1923 /// Returns the smallest height beyond which increasing the height never
1924 /// decreases the preferred width. The preferred width is the value that
1925 /// would be returned by [getMinIntrinsicWidth] for that height.
1926 ///
1927 /// The width argument may give a specific width to assume. The given width
1928 /// can be infinite, meaning that the intrinsic height in an unconstrained
1929 /// environment is being requested. The given width should never be negative
1930 /// or null.
1931 ///
1932 /// This function should only be called on one's children. Calling this
1933 /// function couples the child with the parent so that when the child's layout
1934 /// changes, the parent is notified (via [markNeedsLayout]).
1935 ///
1936 /// Calling this function is expensive as it can result in O(N^2) behavior.
1937 ///
1938 /// Do not override this method. Instead, implement
1939 /// [computeMaxIntrinsicHeight].
1940 @mustCallSuper
1941 double getMaxIntrinsicHeight(double width) {
1942 assert(() {
1943 if (width < 0.0) {
1944 throw FlutterError.fromParts(<DiagnosticsNode>[
1945 ErrorSummary('The width argument to getMaxIntrinsicHeight was negative.'),
1946 ErrorDescription('The argument to getMaxIntrinsicHeight must not be negative or null.'),
1947 ErrorHint(
1948 'If you perform computations on another width before passing it to '
1949 'getMaxIntrinsicHeight, consider using math.max() or double.clamp() '
1950 'to force the value into the valid range.',
1951 ),
1952 ]);
1953 }
1954 return true;
1955 }());
1956 return _computeIntrinsics(_IntrinsicDimension.maxHeight, width, computeMaxIntrinsicHeight);
1957 }
1958
1959 /// Computes the value returned by [getMaxIntrinsicHeight]. Do not call this
1960 /// function directly, instead, call [getMaxIntrinsicHeight].
1961 ///
1962 /// Override in subclasses that implement [performLayout]. Should return the
1963 /// smallest height beyond which increasing the height never decreases the
1964 /// preferred width. The preferred width is the value that would be returned
1965 /// by [computeMinIntrinsicWidth] for that height.
1966 ///
1967 /// If the layout algorithm is strictly width-in-height-out, or is
1968 /// width-in-height-out when the height is unconstrained, then this should
1969 /// return the same value as [computeMinIntrinsicHeight] for the same width.
1970 ///
1971 /// Otherwise, the width argument should be ignored, and the returned value
1972 /// should be equal to or bigger than the value returned by
1973 /// [computeMinIntrinsicHeight].
1974 ///
1975 /// The `width` argument will never be negative or null. It may be infinite.
1976 ///
1977 /// The value returned by this method might not match the size that the object
1978 /// would actually take. For example, a [RenderBox] subclass that always
1979 /// exactly sizes itself using [BoxConstraints.biggest] might well size itself
1980 /// bigger than its max intrinsic size.
1981 ///
1982 /// If this algorithm depends on the intrinsic dimensions of a child, the
1983 /// intrinsic dimensions of that child should be obtained using the functions
1984 /// whose names start with `get`, not `compute`.
1985 ///
1986 /// This function should never return a negative or infinite value.
1987 ///
1988 /// Be sure to set [debugCheckIntrinsicSizes] to true in your unit tests if
1989 /// you do override this method, which will add additional checks to help
1990 /// validate your implementation.
1991 ///
1992 /// See also:
1993 ///
1994 /// * [computeMinIntrinsicWidth], which has usage examples.
1995 @visibleForOverriding
1996 @protected
1997 double computeMaxIntrinsicHeight(double width) {
1998 return 0.0;
1999 }
2000
2001 /// Returns the [Size] that this [RenderBox] would like to be given the
2002 /// provided [BoxConstraints].
2003 ///
2004 /// The size returned by this method is guaranteed to be the same size that
2005 /// this [RenderBox] computes for itself during layout given the same
2006 /// constraints.
2007 ///
2008 /// This function should only be called on one's children. Calling this
2009 /// function couples the child with the parent so that when the child's layout
2010 /// changes, the parent is notified (via [markNeedsLayout]).
2011 ///
2012 /// This layout is called "dry" layout as opposed to the regular "wet" layout
2013 /// run performed by [performLayout] because it computes the desired size for
2014 /// the given constraints without changing any internal state.
2015 ///
2016 /// Calling this function is expensive as it can result in O(N^2) behavior.
2017 ///
2018 /// Do not override this method. Instead, implement [computeDryLayout].
2019 @mustCallSuper
2020 Size getDryLayout(covariant BoxConstraints constraints) {
2021 return _computeIntrinsics(_CachedLayoutCalculation.dryLayout, constraints, _computeDryLayout);
2022 }
2023
2024 bool _computingThisDryLayout = false;
2025 Size _computeDryLayout(BoxConstraints constraints) {
2026 assert(() {
2027 assert(!_computingThisDryLayout);
2028 _computingThisDryLayout = true;
2029 return true;
2030 }());
2031 final Size result = computeDryLayout(constraints);
2032 assert(() {
2033 assert(_computingThisDryLayout);
2034 _computingThisDryLayout = false;
2035 return true;
2036 }());
2037 return result;
2038 }
2039
2040 /// Computes the value returned by [getDryLayout]. Do not call this
2041 /// function directly, instead, call [getDryLayout].
2042 ///
2043 /// Override in subclasses that implement [performLayout] or [performResize]
2044 /// or when setting [sizedByParent] to true without overriding
2045 /// [performResize]. This method should return the [Size] that this
2046 /// [RenderBox] would like to be given the provided [BoxConstraints].
2047 ///
2048 /// The size returned by this method must match the [size] that the
2049 /// [RenderBox] will compute for itself in [performLayout] (or
2050 /// [performResize], if [sizedByParent] is true).
2051 ///
2052 /// If this algorithm depends on the size of a child, the size of that child
2053 /// should be obtained using its [getDryLayout] method.
2054 ///
2055 /// This layout is called "dry" layout as opposed to the regular "wet" layout
2056 /// run performed by [performLayout] because it computes the desired size for
2057 /// the given constraints without changing any internal state.
2058 ///
2059 /// ### When the size cannot be known
2060 ///
2061 /// There are cases where render objects do not have an efficient way to
2062 /// compute their size. For example, the size may computed by a callback about
2063 /// which the render object cannot reason.
2064 ///
2065 /// In such cases, it may be impossible (or at least impractical) to actually
2066 /// return a valid answer. In such cases, the function should call
2067 /// [debugCannotComputeDryLayout] from within an assert and return a dummy
2068 /// value of `const Size(0, 0)`.
2069 @visibleForOverriding
2070 @protected
2071 Size computeDryLayout(covariant BoxConstraints constraints) {
2072 assert(
2073 debugCannotComputeDryLayout(
2074 error: FlutterError.fromParts(<DiagnosticsNode>[
2075 ErrorSummary(
2076 'The ${objectRuntimeType(this, 'RenderBox')} class does not implement "computeDryLayout".',
2077 ),
2078 ErrorHint(
2079 'If you are not writing your own RenderBox subclass, then this is not\n'
2080 'your fault. Contact support: https://github.com/flutter/flutter/issues/new?template=02_bug.yml',
2081 ),
2082 ]),
2083 ),
2084 );
2085 return Size.zero;
2086 }
2087
2088 /// Returns the distance from the top of the box to the first baseline of the
2089 /// box's contents for the given `constraints`, or `null` if this [RenderBox]
2090 /// does not have any baselines.
2091 ///
2092 /// This method calls [computeDryBaseline] under the hood and caches the result.
2093 /// [RenderBox] subclasses typically don't overridden [getDryBaseline]. Instead,
2094 /// consider overriding [computeDryBaseline] such that it returns a baseline
2095 /// location that is consistent with [getDistanceToActualBaseline]. See the
2096 /// documentation for the [computeDryBaseline] method for more details.
2097 ///
2098 /// This method is usually called by the [computeDryBaseline] or the
2099 /// [computeDryLayout] implementation of a parent [RenderBox] to get the
2100 /// baseline location of a [RenderBox] child. Unlike [getDistanceToBaseline],
2101 /// this method takes a [BoxConstraints] as an argument and computes the
2102 /// baseline location as if the [RenderBox] was laid out by the parent using
2103 /// that [BoxConstraints].
2104 ///
2105 /// The "dry" in the method name means this method, like [getDryLayout], has
2106 /// no observable side effects when called, as opposed to "wet" layout methods
2107 /// such as [performLayout] (which changes this [RenderBox]'s [size], and the
2108 /// offsets of its children if any). Since this method does not depend on the
2109 /// current layout, unlike [getDistanceToBaseline], it's ok to call this method
2110 /// when this [RenderBox]'s layout is outdated.
2111 ///
2112 /// Similar to the intrinsic width/height and [getDryLayout], calling this
2113 /// function in [performLayout] is expensive, as it can result in O(N^2) layout
2114 /// performance, where N is the number of render objects in the render subtree.
2115 /// Typically this method should be only called by the parent [RenderBox]'s
2116 /// [computeDryBaseline] or [computeDryLayout] implementation.
2117 double? getDryBaseline(covariant BoxConstraints constraints, TextBaseline baseline) {
2118 final double? baselineOffset = _computeIntrinsics(_CachedLayoutCalculation.baseline, (
2119 constraints,
2120 baseline,
2121 ), _computeDryBaseline).offset;
2122 // This assert makes sure computeDryBaseline always gets called in debug mode,
2123 // in case the computeDryBaseline implementation invokes debugCannotComputeDryLayout.
2124 // This check should be skipped when debugCheckingIntrinsics is true to avoid
2125 // slowing down the app significantly.
2126 assert(
2127 RenderObject.debugCheckingIntrinsics ||
2128 baselineOffset == computeDryBaseline(constraints, baseline),
2129 );
2130 return baselineOffset;
2131 }
2132
2133 bool _computingThisDryBaseline = false;
2134 BaselineOffset _computeDryBaseline((BoxConstraints, TextBaseline) pair) {
2135 assert(() {
2136 assert(!_computingThisDryBaseline);
2137 _computingThisDryBaseline = true;
2138 return true;
2139 }());
2140 final BaselineOffset result = BaselineOffset(computeDryBaseline(pair.$1, pair.$2));
2141 assert(() {
2142 assert(_computingThisDryBaseline);
2143 _computingThisDryBaseline = false;
2144 return true;
2145 }());
2146 return result;
2147 }
2148
2149 /// Computes the value returned by [getDryBaseline].
2150 ///
2151 /// This method is for overriding only and shouldn't be called directly. To
2152 /// get this [RenderBox]'s speculative baseline location for the given
2153 /// `constraints`, call [getDryBaseline] instead.
2154 ///
2155 /// The "dry" in the method name means the implementation must not produce
2156 /// observable side effects when called. For example, it must not change the
2157 /// [size] of the [RenderBox], or its children's paint offsets, otherwise that
2158 /// would results in UI changes when [paint] is called, or hit-testing behavior
2159 /// changes when [hitTest] is called. Moreover, accessing the current layout
2160 /// of this [RenderBox] or child [RenderBox]es (including accessing [size], or
2161 /// `child.size`) usually indicates a bug in the implementation, as the current
2162 /// layout is typically calculated using a set of [BoxConstraints] that's
2163 /// different from the `constraints` given as the first parameter. To get the
2164 /// size of this [RenderBox] or a child [RenderBox] in this method's
2165 /// implementation, use the [getDryLayout] method instead.
2166 ///
2167 /// The implementation must return a value that represents the distance from
2168 /// the top of the box to the first baseline of the box's contents, for the
2169 /// given `constraints`, or `null` if the [RenderBox] has no baselines. It's
2170 /// the same exact value [RenderBox.computeDistanceToActualBaseline] would
2171 /// return, when this [RenderBox] was laid out at `constraints` in the same
2172 /// exact state.
2173 ///
2174 /// Not all [RenderBox]es support dry baseline computation. For example, to
2175 /// compute the dry baseline of a [LayoutBuilder], its `builder` may have to
2176 /// be called with different constraints, which may have side effects such as
2177 /// updating the widget tree, violating the "dry" contract. In such cases the
2178 /// [RenderBox] must call [debugCannotComputeDryLayout] in an assert, and
2179 /// return a dummy baseline offset value (such as `null`).
2180 @visibleForOverriding
2181 @protected
2182 double? computeDryBaseline(covariant BoxConstraints constraints, TextBaseline baseline) {
2183 assert(
2184 debugCannotComputeDryLayout(
2185 error: FlutterError.fromParts(<DiagnosticsNode>[
2186 ErrorSummary(
2187 'The ${objectRuntimeType(this, 'RenderBox')} class does not implement "computeDryBaseline".',
2188 ),
2189 ErrorHint(
2190 'If you are not writing your own RenderBox subclass, then this is not\n'
2191 'your fault. Contact support: https://github.com/flutter/flutter/issues/new?template=02_bug.yml',
2192 ),
2193 ]),
2194 ),
2195 );
2196 return null;
2197 }
2198
2199 static bool _debugDryLayoutCalculationValid = true;
2200
2201 /// Called from [computeDryLayout] or [computeDryBaseline] within an assert if
2202 /// the given [RenderBox] subclass does not support calculating a dry layout.
2203 ///
2204 /// When asserts are enabled and [debugCheckingIntrinsics] is not true, this
2205 /// method will either throw the provided [FlutterError] or it will create and
2206 /// throw a [FlutterError] with the provided `reason`. Otherwise, it will
2207 /// return true.
2208 ///
2209 /// One of the arguments has to be provided.
2210 ///
2211 /// See also:
2212 ///
2213 /// * [computeDryLayout], which lists some reasons why it may not be feasible
2214 /// to compute the dry layout.
2215 bool debugCannotComputeDryLayout({String? reason, FlutterError? error}) {
2216 assert((reason == null) != (error == null));
2217 assert(() {
2218 if (!RenderObject.debugCheckingIntrinsics) {
2219 if (reason != null) {
2220 assert(error == null);
2221 throw FlutterError.fromParts(<DiagnosticsNode>[
2222 ErrorSummary(
2223 'The ${objectRuntimeType(this, 'RenderBox')} class does not support dry layout.',
2224 ),
2225 if (reason.isNotEmpty) ErrorDescription(reason),
2226 ]);
2227 }
2228 assert(error != null);
2229 throw error!;
2230 }
2231 _debugDryLayoutCalculationValid = false;
2232 return true;
2233 }());
2234 return true;
2235 }
2236
2237 /// Whether this render object has undergone layout and has a [size].
2238 bool get hasSize => _size != null;
2239
2240 /// The size of this render box computed during layout.
2241 ///
2242 /// This value is stale whenever this object is marked as needing layout.
2243 /// During [performLayout], do not read the size of a child unless you pass
2244 /// true for parentUsesSize when calling the child's [layout] function.
2245 ///
2246 /// The size of a box should be set only during the box's [performLayout] or
2247 /// [performResize] functions. If you wish to change the size of a box outside
2248 /// of those functions, call [markNeedsLayout] instead to schedule a layout of
2249 /// the box.
2250 Size get size {
2251 assert(hasSize, 'RenderBox was not laid out: $this');
2252 assert(() {
2253 final Size? size = _size;
2254 if (size is _DebugSize) {
2255 assert(size._owner == this);
2256 final RenderObject? parent = this.parent;
2257 // Whether the size getter is accessed during layout (but not in a
2258 // layout callback).
2259 final bool doingRegularLayout =
2260 !(RenderObject.debugActiveLayout?.debugDoingThisLayoutWithCallback ?? true);
2261 final bool sizeAccessAllowed =
2262 !doingRegularLayout ||
2263 debugDoingThisResize ||
2264 debugDoingThisLayout ||
2265 RenderObject.debugActiveLayout == parent && size._canBeUsedByParent;
2266 assert(
2267 sizeAccessAllowed,
2268 'RenderBox.size accessed beyond the scope of resize, layout, or '
2269 'permitted parent access. RenderBox can always access its own size, '
2270 'otherwise, the only object that is allowed to read RenderBox.size '
2271 'is its parent, if they have said they will. It you hit this assert '
2272 'trying to access a child\'s size, pass "parentUsesSize: true" to '
2273 "that child's layout() in ${objectRuntimeType(this, 'RenderBox')}.performLayout.",
2274 );
2275 final RenderBox? renderBoxDoingDryLayout = _computingThisDryLayout
2276 ? this
2277 : (parent is RenderBox && parent._computingThisDryLayout ? parent : null);
2278
2279 assert(
2280 renderBoxDoingDryLayout == null,
2281 'RenderBox.size accessed in '
2282 '${objectRuntimeType(renderBoxDoingDryLayout, 'RenderBox')}.computeDryLayout. '
2283 "The computeDryLayout method must not access the RenderBox's own size, or the size of its child, "
2284 "because it's established in performLayout or performResize using different BoxConstraints.",
2285 );
2286
2287 final RenderBox? renderBoxDoingDryBaseline = _computingThisDryBaseline
2288 ? this
2289 : (parent is RenderBox && parent._computingThisDryBaseline ? parent : null);
2290 assert(
2291 renderBoxDoingDryBaseline == null,
2292
2293 'RenderBox.size accessed in '
2294 '${objectRuntimeType(renderBoxDoingDryBaseline, 'RenderBox')}.computeDryBaseline. '
2295 "The computeDryBaseline method must not access the RenderBox's own size, or the size of its child, "
2296 "because it's established in performLayout or performResize using different BoxConstraints.",
2297 );
2298 assert(size == _size);
2299 }
2300 return true;
2301 }());
2302 return _size ??
2303 (throw StateError('RenderBox was not laid out: $runtimeType#${shortHash(this)}'));
2304 }
2305
2306 Size? _size;
2307
2308 /// Setting the size, in debug mode, triggers some analysis of the render box,
2309 /// as implemented by [debugAssertDoesMeetConstraints], including calling the intrinsic
2310 /// sizing methods and checking that they meet certain invariants.
2311 @protected
2312 set size(Size value) {
2313 assert(!(debugDoingThisResize && debugDoingThisLayout));
2314 assert(sizedByParent || !debugDoingThisResize);
2315 assert(() {
2316 if ((sizedByParent && debugDoingThisResize) || (!sizedByParent && debugDoingThisLayout)) {
2317 return true;
2318 }
2319 assert(!debugDoingThisResize);
2320 final List<DiagnosticsNode> information = <DiagnosticsNode>[
2321 ErrorSummary('RenderBox size setter called incorrectly.'),
2322 ];
2323 if (debugDoingThisLayout) {
2324 assert(sizedByParent);
2325 information.add(
2326 ErrorDescription('It appears that the size setter was called from performLayout().'),
2327 );
2328 } else {
2329 information.add(
2330 ErrorDescription(
2331 'The size setter was called from outside layout (neither performResize() nor performLayout() were being run for this object).',
2332 ),
2333 );
2334 if (owner != null && owner!.debugDoingLayout) {
2335 information.add(
2336 ErrorDescription(
2337 'Only the object itself can set its size. It is a contract violation for other objects to set it.',
2338 ),
2339 );
2340 }
2341 }
2342 if (sizedByParent) {
2343 information.add(
2344 ErrorDescription(
2345 'Because this RenderBox has sizedByParent set to true, it must set its size in performResize().',
2346 ),
2347 );
2348 } else {
2349 information.add(
2350 ErrorDescription(
2351 'Because this RenderBox has sizedByParent set to false, it must set its size in performLayout().',
2352 ),
2353 );
2354 }
2355 throw FlutterError.fromParts(information);
2356 }());
2357 assert(() {
2358 value = debugAdoptSize(value);
2359 return true;
2360 }());
2361 _size = value;
2362 assert(() {
2363 debugAssertDoesMeetConstraints();
2364 return true;
2365 }());
2366 }
2367
2368 /// Claims ownership of the given [Size].
2369 ///
2370 /// In debug mode, the [RenderBox] class verifies that [Size] objects obtained
2371 /// from other [RenderBox] objects are only used according to the semantics of
2372 /// the [RenderBox] protocol, namely that a [Size] from a [RenderBox] can only
2373 /// be used by its parent, and then only if `parentUsesSize` was set.
2374 ///
2375 /// Sometimes, a [Size] that can validly be used ends up no longer being valid
2376 /// over time. The common example is a [Size] taken from a child that is later
2377 /// removed from the parent. In such cases, this method can be called to first
2378 /// check whether the size can legitimately be used, and if so, to then create
2379 /// a new [Size] that can be used going forward, regardless of what happens to
2380 /// the original owner.
2381 Size debugAdoptSize(Size value) {
2382 Size result = value;
2383 assert(() {
2384 if (value is _DebugSize) {
2385 if (value._owner != this) {
2386 if (value._owner.parent != this) {
2387 throw FlutterError.fromParts(<DiagnosticsNode>[
2388 ErrorSummary('The size property was assigned a size inappropriately.'),
2389 describeForError('The following render object'),
2390 value._owner.describeForError('...was assigned a size obtained from'),
2391 ErrorDescription(
2392 'However, this second render object is not, or is no longer, a '
2393 'child of the first, and it is therefore a violation of the '
2394 'RenderBox layout protocol to use that size in the layout of the '
2395 'first render object.',
2396 ),
2397 ErrorHint(
2398 'If the size was obtained at a time where it was valid to read '
2399 'the size (because the second render object above was a child '
2400 'of the first at the time), then it should be adopted using '
2401 'debugAdoptSize at that time.',
2402 ),
2403 ErrorHint(
2404 'If the size comes from a grandchild or a render object from an '
2405 'entirely different part of the render tree, then there is no '
2406 'way to be notified when the size changes and therefore attempts '
2407 'to read that size are almost certainly a source of bugs. A different '
2408 'approach should be used.',
2409 ),
2410 ]);
2411 }
2412 if (!value._canBeUsedByParent) {
2413 throw FlutterError.fromParts(<DiagnosticsNode>[
2414 ErrorSummary("A child's size was used without setting parentUsesSize."),
2415 describeForError('The following render object'),
2416 value._owner.describeForError('...was assigned a size obtained from its child'),
2417 ErrorDescription(
2418 'However, when the child was laid out, the parentUsesSize argument '
2419 'was not set or set to false. Subsequently this transpired to be '
2420 'inaccurate: the size was nonetheless used by the parent.\n'
2421 'It is important to tell the framework if the size will be used or not '
2422 'as several important performance optimizations can be made if the '
2423 'size will not be used by the parent.',
2424 ),
2425 ]);
2426 }
2427 }
2428 }
2429 result = _DebugSize(value, this, debugCanParentUseSize);
2430 return true;
2431 }());
2432 return result;
2433 }
2434
2435 @override
2436 Rect get semanticBounds => Offset.zero & size;
2437
2438 @override
2439 void debugResetSize() {
2440 // updates the value of size._canBeUsedByParent if necessary
2441 size = size; // ignore: no_self_assignments
2442 }
2443
2444 static bool _debugDoingBaseline = false;
2445 static bool _debugSetDoingBaseline(bool value) {
2446 _debugDoingBaseline = value;
2447 return true;
2448 }
2449
2450 /// Returns the distance from the y-coordinate of the position of the box to
2451 /// the y-coordinate of the first given baseline in the box's contents.
2452 ///
2453 /// Used by certain layout models to align adjacent boxes on a common
2454 /// baseline, regardless of padding, font size differences, etc. If there is
2455 /// no baseline, this function returns the distance from the y-coordinate of
2456 /// the position of the box to the y-coordinate of the bottom of the box
2457 /// (i.e., the height of the box) unless the caller passes true
2458 /// for `onlyReal`, in which case the function returns null.
2459 ///
2460 /// Only call this function after calling [layout] on this box. You
2461 /// are only allowed to call this from the parent of this box during
2462 /// that parent's [performLayout] or [paint] functions.
2463 ///
2464 /// When implementing a [RenderBox] subclass, to override the baseline
2465 /// computation, override [computeDistanceToActualBaseline].
2466 ///
2467 /// See also:
2468 ///
2469 /// * [getDryBaseline], which returns the baseline location of this
2470 /// [RenderBox] at a certain [BoxConstraints].
2471 double? getDistanceToBaseline(TextBaseline baseline, {bool onlyReal = false}) {
2472 assert(
2473 !_debugDoingBaseline,
2474 'Please see the documentation for computeDistanceToActualBaseline for the required calling conventions of this method.',
2475 );
2476 assert(!debugNeedsLayout || RenderObject.debugCheckingIntrinsics);
2477 assert(
2478 RenderObject.debugCheckingIntrinsics ||
2479 switch (owner!) {
2480 PipelineOwner(debugDoingLayout: true) =>
2481 RenderObject.debugActiveLayout == parent && parent!.debugDoingThisLayout,
2482 PipelineOwner(debugDoingPaint: true) =>
2483 RenderObject.debugActivePaint == parent && parent!.debugDoingThisPaint ||
2484 (RenderObject.debugActivePaint == this && debugDoingThisPaint),
2485 PipelineOwner() => false,
2486 },
2487 );
2488 assert(_debugSetDoingBaseline(true));
2489 final double? result;
2490 try {
2491 result = getDistanceToActualBaseline(baseline);
2492 } finally {
2493 assert(_debugSetDoingBaseline(false));
2494 }
2495 if (result == null && !onlyReal) {
2496 return size.height;
2497 }
2498 return result;
2499 }
2500
2501 /// Calls [computeDistanceToActualBaseline] and caches the result.
2502 ///
2503 /// This function must only be called from [getDistanceToBaseline] and
2504 /// [computeDistanceToActualBaseline]. Do not call this function directly from
2505 /// outside those two methods.
2506 @protected
2507 @mustCallSuper
2508 double? getDistanceToActualBaseline(TextBaseline baseline) {
2509 assert(
2510 _debugDoingBaseline,
2511 'Please see the documentation for computeDistanceToActualBaseline for the required calling conventions of this method.',
2512 );
2513 return _computeIntrinsics(
2514 _CachedLayoutCalculation.baseline,
2515 (constraints, baseline),
2516 ((BoxConstraints, TextBaseline) pair) =>
2517 BaselineOffset(computeDistanceToActualBaseline(pair.$2)),
2518 ).offset;
2519 }
2520
2521 /// Returns the distance from the y-coordinate of the position of the box to
2522 /// the y-coordinate of the first given baseline in the box's contents, if
2523 /// any, or null otherwise.
2524 ///
2525 /// Do not call this function directly. If you need to know the baseline of a
2526 /// child from an invocation of [performLayout] or [paint], call
2527 /// [getDistanceToBaseline].
2528 ///
2529 /// Subclasses should override this method to supply the distances to their
2530 /// baselines. When implementing this method, there are generally three
2531 /// strategies:
2532 ///
2533 /// * For classes that use the [ContainerRenderObjectMixin] child model,
2534 /// consider mixing in the [RenderBoxContainerDefaultsMixin] class and
2535 /// using
2536 /// [RenderBoxContainerDefaultsMixin.defaultComputeDistanceToFirstActualBaseline].
2537 ///
2538 /// * For classes that define a particular baseline themselves, return that
2539 /// value directly.
2540 ///
2541 /// * For classes that have a child to which they wish to defer the
2542 /// computation, call [getDistanceToActualBaseline] on the child (not
2543 /// [computeDistanceToActualBaseline], the internal implementation, and not
2544 /// [getDistanceToBaseline], the public entry point for this API).
2545 @visibleForOverriding
2546 @protected
2547 double? computeDistanceToActualBaseline(TextBaseline baseline) {
2548 assert(
2549 _debugDoingBaseline,
2550 'Please see the documentation for computeDistanceToActualBaseline for the required calling conventions of this method.',
2551 );
2552 return null;
2553 }
2554
2555 /// The box constraints most recently received from the parent.
2556 @override
2557 BoxConstraints get constraints => super.constraints as BoxConstraints;
2558
2559 @override
2560 void debugAssertDoesMeetConstraints() {
2561 assert(() {
2562 if (!hasSize) {
2563 final DiagnosticsNode contract;
2564 if (sizedByParent) {
2565 contract = ErrorDescription(
2566 'Because this RenderBox has sizedByParent set to true, it must set its size in performResize().',
2567 );
2568 } else {
2569 contract = ErrorDescription(
2570 'Because this RenderBox has sizedByParent set to false, it must set its size in performLayout().',
2571 );
2572 }
2573 throw FlutterError.fromParts(<DiagnosticsNode>[
2574 ErrorSummary('RenderBox did not set its size during layout.'),
2575 contract,
2576 ErrorDescription(
2577 'It appears that this did not happen; layout completed, but the size property is still null.',
2578 ),
2579 DiagnosticsProperty<RenderBox>(
2580 'The RenderBox in question is',
2581 this,
2582 style: DiagnosticsTreeStyle.errorProperty,
2583 ),
2584 ]);
2585 }
2586 // verify that the size is not infinite
2587 if (!_size!.isFinite) {
2588 final List<DiagnosticsNode> information = <DiagnosticsNode>[
2589 ErrorSummary('$runtimeType object was given an infinite size during layout.'),
2590 ErrorDescription(
2591 'This probably means that it is a render object that tries to be '
2592 'as big as possible, but it was put inside another render object '
2593 'that allows its children to pick their own size.',
2594 ),
2595 ];
2596 if (!constraints.hasBoundedWidth) {
2597 RenderBox node = this;
2598 while (!node.constraints.hasBoundedWidth && node.parent is RenderBox) {
2599 node = node.parent! as RenderBox;
2600 }
2601
2602 information.add(
2603 node.describeForError(
2604 'The nearest ancestor providing an unbounded width constraint is',
2605 ),
2606 );
2607 }
2608 if (!constraints.hasBoundedHeight) {
2609 RenderBox node = this;
2610 while (!node.constraints.hasBoundedHeight && node.parent is RenderBox) {
2611 node = node.parent! as RenderBox;
2612 }
2613
2614 information.add(
2615 node.describeForError(
2616 'The nearest ancestor providing an unbounded height constraint is',
2617 ),
2618 );
2619 }
2620 throw FlutterError.fromParts(<DiagnosticsNode>[
2621 ...information,
2622 DiagnosticsProperty<BoxConstraints>(
2623 'The constraints that applied to the $runtimeType were',
2624 constraints,
2625 style: DiagnosticsTreeStyle.errorProperty,
2626 ),
2627 DiagnosticsProperty<Size>(
2628 'The exact size it was given was',
2629 _size,
2630 style: DiagnosticsTreeStyle.errorProperty,
2631 ),
2632 ErrorHint('See https://flutter.dev/to/unbounded-constraints for more information.'),
2633 ]);
2634 }
2635 // verify that the size is within the constraints
2636 if (!constraints.isSatisfiedBy(_size!)) {
2637 throw FlutterError.fromParts(<DiagnosticsNode>[
2638 ErrorSummary('$runtimeType does not meet its constraints.'),
2639 DiagnosticsProperty<BoxConstraints>(
2640 'Constraints',
2641 constraints,
2642 style: DiagnosticsTreeStyle.errorProperty,
2643 ),
2644 DiagnosticsProperty<Size>('Size', _size, style: DiagnosticsTreeStyle.errorProperty),
2645 ErrorHint(
2646 'If you are not writing your own RenderBox subclass, then this is not '
2647 'your fault. Contact support: https://github.com/flutter/flutter/issues/new?template=02_bug.yml',
2648 ),
2649 ]);
2650 }
2651 if (debugCheckIntrinsicSizes) {
2652 // verify that the intrinsics are sane
2653 assert(!RenderObject.debugCheckingIntrinsics);
2654 RenderObject.debugCheckingIntrinsics = true;
2655 final List<DiagnosticsNode> failures = <DiagnosticsNode>[];
2656
2657 double testIntrinsic(
2658 double Function(double extent) function,
2659 String name,
2660 double constraint,
2661 ) {
2662 final double result = function(constraint);
2663 if (result < 0) {
2664 failures.add(
2665 ErrorDescription(' * $name($constraint) returned a negative value: $result'),
2666 );
2667 }
2668 if (!result.isFinite) {
2669 failures.add(
2670 ErrorDescription(' * $name($constraint) returned a non-finite value: $result'),
2671 );
2672 }
2673 return result;
2674 }
2675
2676 void testIntrinsicsForValues(
2677 double Function(double extent) getMin,
2678 double Function(double extent) getMax,
2679 String name,
2680 double constraint,
2681 ) {
2682 final double min = testIntrinsic(getMin, 'getMinIntrinsic$name', constraint);
2683 final double max = testIntrinsic(getMax, 'getMaxIntrinsic$name', constraint);
2684 if (min > max) {
2685 failures.add(
2686 ErrorDescription(
2687 ' * getMinIntrinsic$name($constraint) returned a larger value ($min) than getMaxIntrinsic$name($constraint) ($max)',
2688 ),
2689 );
2690 }
2691 }
2692
2693 try {
2694 testIntrinsicsForValues(
2695 getMinIntrinsicWidth,
2696 getMaxIntrinsicWidth,
2697 'Width',
2698 double.infinity,
2699 );
2700 testIntrinsicsForValues(
2701 getMinIntrinsicHeight,
2702 getMaxIntrinsicHeight,
2703 'Height',
2704 double.infinity,
2705 );
2706 if (constraints.hasBoundedWidth) {
2707 testIntrinsicsForValues(
2708 getMinIntrinsicWidth,
2709 getMaxIntrinsicWidth,
2710 'Width',
2711 constraints.maxHeight,
2712 );
2713 }
2714 if (constraints.hasBoundedHeight) {
2715 testIntrinsicsForValues(
2716 getMinIntrinsicHeight,
2717 getMaxIntrinsicHeight,
2718 'Height',
2719 constraints.maxWidth,
2720 );
2721 }
2722 // TODO(ianh): Test that values are internally consistent in more ways than the above.
2723 } finally {
2724 RenderObject.debugCheckingIntrinsics = false;
2725 }
2726
2727 if (failures.isNotEmpty) {
2728 // TODO(jacobr): consider nesting the failures object so it is collapsible.
2729 throw FlutterError.fromParts(<DiagnosticsNode>[
2730 ErrorSummary(
2731 'The intrinsic dimension methods of the $runtimeType class returned values that violate the intrinsic protocol contract.',
2732 ),
2733 ErrorDescription(
2734 'The following ${failures.length > 1 ? "failures" : "failure"} was detected:',
2735 ), // should this be tagged as an error or not?
2736 ...failures,
2737 ErrorHint(
2738 'If you are not writing your own RenderBox subclass, then this is not\n'
2739 'your fault. Contact support: https://github.com/flutter/flutter/issues/new?template=02_bug.yml',
2740 ),
2741 ]);
2742 }
2743
2744 // Checking that getDryLayout computes the same size.
2745 _debugDryLayoutCalculationValid = true;
2746 RenderObject.debugCheckingIntrinsics = true;
2747 final Size dryLayoutSize;
2748 try {
2749 dryLayoutSize = getDryLayout(constraints);
2750 } finally {
2751 RenderObject.debugCheckingIntrinsics = false;
2752 }
2753 if (_debugDryLayoutCalculationValid && dryLayoutSize != _size) {
2754 throw FlutterError.fromParts(<DiagnosticsNode>[
2755 ErrorSummary(
2756 'The size given to the ${objectRuntimeType(this, 'RenderBox')} class differs from the size computed by computeDryLayout.',
2757 ),
2758 ErrorDescription(
2759 'The size computed in ${sizedByParent ? 'performResize' : 'performLayout'} '
2760 'is $size, which is different from $dryLayoutSize, which was computed by computeDryLayout.',
2761 ),
2762 ErrorDescription('The constraints used were $constraints.'),
2763 ErrorHint(
2764 'If you are not writing your own RenderBox subclass, then this is not\n'
2765 'your fault. Contact support: https://github.com/flutter/flutter/issues/new?template=02_bug.yml',
2766 ),
2767 ]);
2768 }
2769 }
2770 return true;
2771 }());
2772 }
2773
2774 void _debugVerifyDryBaselines() {
2775 assert(() {
2776 final List<DiagnosticsNode> messages = <DiagnosticsNode>[
2777 ErrorDescription('The constraints used were $constraints.'),
2778 ErrorHint(
2779 'If you are not writing your own RenderBox subclass, then this is not\n'
2780 'your fault. Contact support: https://github.com/flutter/flutter/issues/new?template=02_bug.yml',
2781 ),
2782 ];
2783
2784 for (final TextBaseline baseline in TextBaseline.values) {
2785 assert(!RenderObject.debugCheckingIntrinsics);
2786 RenderObject.debugCheckingIntrinsics = true;
2787 _debugDryLayoutCalculationValid = true;
2788 final double? dryBaseline;
2789 final double? realBaseline;
2790 try {
2791 dryBaseline = getDryBaseline(constraints, baseline);
2792 realBaseline = getDistanceToBaseline(baseline, onlyReal: true);
2793 } finally {
2794 RenderObject.debugCheckingIntrinsics = false;
2795 }
2796 assert(!RenderObject.debugCheckingIntrinsics);
2797 if (!_debugDryLayoutCalculationValid || dryBaseline == realBaseline) {
2798 continue;
2799 }
2800 if ((dryBaseline == null) != (realBaseline == null)) {
2801 final (String methodReturnedNull, String methodReturnedNonNull) = dryBaseline == null
2802 ? ('computeDryBaseline', 'computeDistanceToActualBaseline')
2803 : ('computeDistanceToActualBaseline', 'computeDryBaseline');
2804 throw FlutterError.fromParts(<DiagnosticsNode>[
2805 ErrorSummary(
2806 'The $baseline location returned by ${objectRuntimeType(this, 'RenderBox')}.computeDistanceToActualBaseline '
2807 'differs from the baseline location computed by computeDryBaseline.',
2808 ),
2809 ErrorDescription(
2810 'The $methodReturnedNull method returned null while the $methodReturnedNonNull returned a non-null $baseline of ${dryBaseline ?? realBaseline}. '
2811 'Did you forget to implement $methodReturnedNull for ${objectRuntimeType(this, 'RenderBox')}?',
2812 ),
2813 ...messages,
2814 ]);
2815 } else {
2816 throw FlutterError.fromParts(<DiagnosticsNode>[
2817 ErrorSummary(
2818 'The $baseline location returned by ${objectRuntimeType(this, 'RenderBox')}.computeDistanceToActualBaseline '
2819 'differs from the baseline location computed by computeDryBaseline.',
2820 ),
2821 DiagnosticsProperty<RenderObject>('The RenderBox was', this),
2822 ErrorDescription(
2823 'The computeDryBaseline method returned $dryBaseline,\n'
2824 'while the computeDistanceToActualBaseline method returned $realBaseline.\n'
2825 'Consider checking the implementations of the following methods on the ${objectRuntimeType(this, 'RenderBox')} class and make sure they are consistent:\n'
2826 ' * computeDistanceToActualBaseline\n'
2827 ' * computeDryBaseline\n'
2828 ' * performLayout\n',
2829 ),
2830 ...messages,
2831 ]);
2832 }
2833 }
2834 return true;
2835 }());
2836 }
2837
2838 @override
2839 void markNeedsLayout() {
2840 // If `_layoutCacheStorage.clear` returns true, then this [RenderBox]'s layout
2841 // is used by the parent's layout algorithm (it's possible that the parent
2842 // only used the intrinsics for paint, but there's no good way to detect that
2843 // so we conservatively assume it's a layout dependency).
2844 //
2845 // A render object's performLayout implementation may depend on the baseline
2846 // location or the intrinsic dimensions of a descendant, even when there are
2847 // relayout boundaries between them. The `_layoutCacheStorage` being non-empty
2848 // indicates that the parent depended on this RenderBox's baseline location,
2849 // or intrinsic sizes, and thus may need relayout, regardless of relayout
2850 // boundaries.
2851 //
2852 // Some calculations may fail (dry baseline, for example). The layout
2853 // dependency is still established, but only from the RenderBox that failed
2854 // to compute the dry baseline to the ancestor that queried the dry baseline.
2855 if (_layoutCacheStorage.clear() && parent != null) {
2856 markParentNeedsLayout();
2857 return;
2858 }
2859 super.markNeedsLayout();
2860 }
2861
2862 /// {@macro flutter.rendering.RenderObject.performResize}
2863 ///
2864 /// By default this method sets [size] to the result of [computeDryLayout]
2865 /// called with the current [constraints]. Instead of overriding this method,
2866 /// consider overriding [computeDryLayout].
2867 @override
2868 void performResize() {
2869 // default behavior for subclasses that have sizedByParent = true
2870 size = computeDryLayout(constraints);
2871 assert(size.isFinite);
2872 }
2873
2874 @override
2875 void performLayout() {
2876 assert(() {
2877 if (!sizedByParent) {
2878 throw FlutterError.fromParts(<DiagnosticsNode>[
2879 ErrorSummary('$runtimeType did not implement performLayout().'),
2880 ErrorHint(
2881 'RenderBox subclasses need to either override performLayout() to '
2882 'set a size and lay out any children, or, set sizedByParent to true '
2883 'so that performResize() sizes the render object.',
2884 ),
2885 ]);
2886 }
2887 return true;
2888 }());
2889 }
2890
2891 /// Determines the set of render objects located at the given position.
2892 ///
2893 /// Returns true, and adds any render objects that contain the point to the
2894 /// given hit test result, if this render object or one of its descendants
2895 /// absorbs the hit (preventing objects below this one from being hit).
2896 /// Returns false if the hit can continue to other objects below this one.
2897 ///
2898 /// The caller is responsible for transforming [position] from global
2899 /// coordinates to its location relative to the origin of this [RenderBox].
2900 /// This [RenderBox] is responsible for checking whether the given position is
2901 /// within its bounds.
2902 ///
2903 /// If transforming is necessary, [BoxHitTestResult.addWithPaintTransform],
2904 /// [BoxHitTestResult.addWithPaintOffset], or
2905 /// [BoxHitTestResult.addWithRawTransform] need to be invoked by the caller
2906 /// to record the required transform operations in the [HitTestResult]. These
2907 /// methods will also help with applying the transform to `position`.
2908 ///
2909 /// Hit testing requires layout to be up-to-date but does not require painting
2910 /// to be up-to-date. That means a render object can rely upon [performLayout]
2911 /// having been called in [hitTest] but cannot rely upon [paint] having been
2912 /// called. For example, a render object might be a child of a [RenderOpacity]
2913 /// object, which calls [hitTest] on its children when its opacity is zero
2914 /// even though it does not [paint] its children.
2915 bool hitTest(BoxHitTestResult result, {required Offset position}) {
2916 assert(() {
2917 if (!hasSize) {
2918 if (debugNeedsLayout) {
2919 throw FlutterError.fromParts(<DiagnosticsNode>[
2920 ErrorSummary('Cannot hit test a render box that has never been laid out.'),
2921 describeForError('The hitTest() method was called on this RenderBox'),
2922 ErrorDescription(
2923 "Unfortunately, this object's geometry is not known at this time, "
2924 'probably because it has never been laid out. '
2925 'This means it cannot be accurately hit-tested.',
2926 ),
2927 ErrorHint(
2928 'If you are trying '
2929 'to perform a hit test during the layout phase itself, make sure '
2930 "you only hit test nodes that have completed layout (e.g. the node's "
2931 'children, after their layout() method has been called).',
2932 ),
2933 ]);
2934 }
2935 throw FlutterError.fromParts(<DiagnosticsNode>[
2936 ErrorSummary('Cannot hit test a render box with no size.'),
2937 describeForError('The hitTest() method was called on this RenderBox'),
2938 ErrorDescription(
2939 'Although this node is not marked as needing layout, '
2940 'its size is not set.',
2941 ),
2942 ErrorHint(
2943 'A RenderBox object must have an '
2944 'explicit size before it can be hit-tested. Make sure '
2945 'that the RenderBox in question sets its size during layout.',
2946 ),
2947 ]);
2948 }
2949 return true;
2950 }());
2951 if (_size!.contains(position)) {
2952 if (hitTestChildren(result, position: position) || hitTestSelf(position)) {
2953 result.add(BoxHitTestEntry(this, position));
2954 return true;
2955 }
2956 }
2957 return false;
2958 }
2959
2960 /// Override this method if this render object can be hit even if its
2961 /// children were not hit.
2962 ///
2963 /// Returns true if the specified `position` should be considered a hit
2964 /// on this render object.
2965 ///
2966 /// The caller is responsible for transforming [position] from global
2967 /// coordinates to its location relative to the origin of this [RenderBox].
2968 /// This [RenderBox] is responsible for checking whether the given position is
2969 /// within its bounds.
2970 ///
2971 /// Used by [hitTest]. If you override [hitTest] and do not call this
2972 /// function, then you don't need to implement this function.
2973 @protected
2974 bool hitTestSelf(Offset position) => false;
2975
2976 /// Override this method to check whether any children are located at the
2977 /// given position.
2978 ///
2979 /// Subclasses should return true if at least one child reported a hit at the
2980 /// specified position.
2981 ///
2982 /// Typically children should be hit-tested in reverse paint order so that
2983 /// hit tests at locations where children overlap hit the child that is
2984 /// visually "on top" (i.e., paints later).
2985 ///
2986 /// The caller is responsible for transforming [position] from global
2987 /// coordinates to its location relative to the origin of this [RenderBox].
2988 /// Likewise, this [RenderBox] is responsible for transforming the position
2989 /// that it passes to its children when it calls [hitTest] on each child.
2990 ///
2991 /// If transforming is necessary, [BoxHitTestResult.addWithPaintTransform],
2992 /// [BoxHitTestResult.addWithPaintOffset], or
2993 /// [BoxHitTestResult.addWithRawTransform] need to be invoked by subclasses to
2994 /// record the required transform operations in the [BoxHitTestResult]. These
2995 /// methods will also help with applying the transform to `position`.
2996 ///
2997 /// Used by [hitTest]. If you override [hitTest] and do not call this
2998 /// function, then you don't need to implement this function.
2999 @protected
3000 bool hitTestChildren(BoxHitTestResult result, {required Offset position}) => false;
3001
3002 /// Multiply the transform from the parent's coordinate system to this box's
3003 /// coordinate system into the given transform.
3004 ///
3005 /// This function is used to convert coordinate systems between boxes.
3006 /// Subclasses that apply transforms during painting should override this
3007 /// function to factor those transforms into the calculation.
3008 ///
3009 /// The [RenderBox] implementation takes care of adjusting the matrix for the
3010 /// position of the given child as determined during layout and stored on the
3011 /// child's [parentData] in the [BoxParentData.offset] field.
3012 @override
3013 void applyPaintTransform(RenderObject child, Matrix4 transform) {
3014 assert(child.parent == this);
3015 assert(() {
3016 if (child.parentData is! BoxParentData) {
3017 throw FlutterError.fromParts(<DiagnosticsNode>[
3018 ErrorSummary('$runtimeType does not implement applyPaintTransform.'),
3019 describeForError('The following $runtimeType object'),
3020 child.describeForError(
3021 '...did not use a BoxParentData class for the parentData field of the following child',
3022 ),
3023 ErrorDescription('The $runtimeType class inherits from RenderBox.'),
3024 ErrorHint(
3025 'The default applyPaintTransform implementation provided by RenderBox assumes that the '
3026 'children all use BoxParentData objects for their parentData field. '
3027 'Since $runtimeType does not in fact use that ParentData class for its children, it must '
3028 'provide an implementation of applyPaintTransform that supports the specific ParentData '
3029 'subclass used by its children (which apparently is ${child.parentData.runtimeType}).',
3030 ),
3031 ]);
3032 }
3033 return true;
3034 }());
3035 final BoxParentData childParentData = child.parentData! as BoxParentData;
3036 final Offset offset = childParentData.offset;
3037 transform.translateByDouble(offset.dx, offset.dy, 0, 1);
3038 }
3039
3040 /// Convert the given point from the global coordinate system in logical pixels
3041 /// to the local coordinate system for this box.
3042 ///
3043 /// This method will un-project the point from the screen onto the widget,
3044 /// which makes it different from [MatrixUtils.transformPoint].
3045 ///
3046 /// If the transform from global coordinates to local coordinates is
3047 /// degenerate, this function returns [Offset.zero].
3048 ///
3049 /// If `ancestor` is non-null, this function converts the given point from the
3050 /// coordinate system of `ancestor` (which must be an ancestor of this render
3051 /// object) instead of from the global coordinate system.
3052 ///
3053 /// This method is implemented in terms of [getTransformTo].
3054 Offset globalToLocal(Offset point, {RenderObject? ancestor}) {
3055 // We want to find point (p) that corresponds to a given point on the
3056 // screen (s), but that also physically resides on the local render plane,
3057 // so that it is useful for visually accurate gesture processing in the
3058 // local space. For that, we can't simply transform 2D screen point to
3059 // the 3D local space since the screen space lacks the depth component |z|,
3060 // and so there are many 3D points that correspond to the screen point.
3061 // We must first unproject the screen point onto the render plane to find
3062 // the true 3D point that corresponds to the screen point.
3063 // We do orthogonal unprojection after undoing perspective, in local space.
3064 // The render plane is specified by renderBox offset (o) and Z axis (n).
3065 // Unprojection is done by finding the intersection of the view vector (d)
3066 // with the local X-Y plane: (o-s).dot(n) == (p-s).dot(n), (p-s) == |z|*d.
3067 final Matrix4 transform = getTransformTo(ancestor);
3068 final double det = transform.invert();
3069 if (det == 0.0) {
3070 return Offset.zero;
3071 }
3072 final Vector3 n = Vector3(0.0, 0.0, 1.0);
3073 final Vector3 i = transform.perspectiveTransform(Vector3(0.0, 0.0, 0.0));
3074 final Vector3 d = transform.perspectiveTransform(Vector3(0.0, 0.0, 1.0)) - i;
3075 final Vector3 s = transform.perspectiveTransform(Vector3(point.dx, point.dy, 0.0));
3076 final Vector3 p = s - d * (n.dot(s) / n.dot(d));
3077 return Offset(p.x, p.y);
3078 }
3079
3080 /// Convert the given point from the local coordinate system for this box to
3081 /// the global coordinate system in logical pixels.
3082 ///
3083 /// If `ancestor` is non-null, this function converts the given point to the
3084 /// coordinate system of `ancestor` (which must be an ancestor of this render
3085 /// object) instead of to the global coordinate system.
3086 ///
3087 /// This method is implemented in terms of [getTransformTo]. If the transform
3088 /// matrix puts the given `point` on the line at infinity (for instance, when
3089 /// the transform matrix is the zero matrix), this method returns (NaN, NaN).
3090 Offset localToGlobal(Offset point, {RenderObject? ancestor}) {
3091 return MatrixUtils.transformPoint(getTransformTo(ancestor), point);
3092 }
3093
3094 /// Returns a rectangle that contains all the pixels painted by this box.
3095 ///
3096 /// The paint bounds can be larger or smaller than [size], which is the amount
3097 /// of space this box takes up during layout. For example, if this box casts a
3098 /// shadow, that shadow might extend beyond the space allocated to this box
3099 /// during layout.
3100 ///
3101 /// The paint bounds are used to size the buffers into which this box paints.
3102 /// If the box attempts to paints outside its paint bounds, there might not be
3103 /// enough memory allocated to represent the box's visual appearance, which
3104 /// can lead to undefined behavior.
3105 ///
3106 /// The returned paint bounds are in the local coordinate system of this box.
3107 @override
3108 Rect get paintBounds => Offset.zero & size;
3109
3110 /// Override this method to handle pointer events that hit this render object.
3111 ///
3112 /// For [RenderBox] objects, the `entry` argument is a [BoxHitTestEntry]. From this
3113 /// object you can determine the [PointerDownEvent]'s position in local coordinates.
3114 /// (This is useful because [PointerEvent.position] is in global coordinates.)
3115 ///
3116 /// Implementations of this method should call [debugHandleEvent] as follows,
3117 /// so that they support [debugPaintPointersEnabled]:
3118 ///
3119 /// ```dart
3120 /// class RenderFoo extends RenderBox {
3121 /// // ...
3122 ///
3123 /// @override
3124 /// void handleEvent(PointerEvent event, HitTestEntry entry) {
3125 /// assert(debugHandleEvent(event, entry));
3126 /// // ... handle the event ...
3127 /// }
3128 ///
3129 /// // ...
3130 /// }
3131 /// ```
3132 @override
3133 void handleEvent(PointerEvent event, BoxHitTestEntry entry) {
3134 super.handleEvent(event, entry);
3135 }
3136
3137 int _debugActivePointers = 0;
3138
3139 /// Implements the [debugPaintPointersEnabled] debugging feature.
3140 ///
3141 /// [RenderBox] subclasses that implement [handleEvent] should call
3142 /// [debugHandleEvent] from their [handleEvent] method, as follows:
3143 ///
3144 /// ```dart
3145 /// class RenderFoo extends RenderBox {
3146 /// // ...
3147 ///
3148 /// @override
3149 /// void handleEvent(PointerEvent event, HitTestEntry entry) {
3150 /// assert(debugHandleEvent(event, entry));
3151 /// // ... handle the event ...
3152 /// }
3153 ///
3154 /// // ...
3155 /// }
3156 /// ```
3157 ///
3158 /// If you call this for a [PointerDownEvent], make sure you also call it for
3159 /// the corresponding [PointerUpEvent] or [PointerCancelEvent].
3160 bool debugHandleEvent(PointerEvent event, HitTestEntry entry) {
3161 assert(() {
3162 if (debugPaintPointersEnabled) {
3163 if (event is PointerDownEvent) {
3164 _debugActivePointers += 1;
3165 } else if (event is PointerUpEvent || event is PointerCancelEvent) {
3166 _debugActivePointers -= 1;
3167 }
3168 markNeedsPaint();
3169 }
3170 return true;
3171 }());
3172 return true;
3173 }
3174
3175 @override
3176 void debugPaint(PaintingContext context, Offset offset) {
3177 assert(() {
3178 // Only perform the baseline checks after `PipelineOwner.flushLayout` completes.
3179 // We can't run this check in the same places we run other intrinsics checks
3180 // (in the `RenderBox.size` setter, or after `performResize`), because
3181 // `getDistanceToBaseline` may depend on the layout of the child so it's
3182 // the safest to only call `getDistanceToBaseline` after the entire tree
3183 // finishes doing layout.
3184 //
3185 // Descendant `RenderObject`s typically call `debugPaint` before their
3186 // parents do. This means the baseline implementations are checked from
3187 // descendants to ancestors, allowing us to spot the `RenderBox` with an
3188 // inconsistent implementation, instead of its ancestors that only reported
3189 // inconsistent baseline values because one of its ancestors has an
3190 // inconsistent implementation.
3191 if (debugCheckIntrinsicSizes) {
3192 _debugVerifyDryBaselines();
3193 }
3194 if (debugPaintSizeEnabled) {
3195 debugPaintSize(context, offset);
3196 }
3197 if (debugPaintBaselinesEnabled) {
3198 debugPaintBaselines(context, offset);
3199 }
3200 if (debugPaintPointersEnabled) {
3201 debugPaintPointers(context, offset);
3202 }
3203 return true;
3204 }());
3205 }
3206
3207 /// In debug mode, paints a border around this render box.
3208 ///
3209 /// Called for every [RenderBox] when [debugPaintSizeEnabled] is true.
3210 @protected
3211 @visibleForTesting
3212 void debugPaintSize(PaintingContext context, Offset offset) {
3213 assert(() {
3214 final Paint paint = Paint()
3215 ..style = PaintingStyle.stroke
3216 ..strokeWidth = 1.0
3217 ..color = const Color(0xFF00FFFF);
3218 context.canvas.drawRect((offset & size).deflate(0.5), paint);
3219 return true;
3220 }());
3221 }
3222
3223 /// In debug mode, paints a line for each baseline.
3224 ///
3225 /// Called for every [RenderBox] when [debugPaintBaselinesEnabled] is true.
3226 @protected
3227 void debugPaintBaselines(PaintingContext context, Offset offset) {
3228 assert(() {
3229 final Paint paint = Paint()
3230 ..style = PaintingStyle.stroke
3231 ..strokeWidth = 0.25;
3232 Path path;
3233 // ideographic baseline
3234 final double? baselineI = getDistanceToBaseline(TextBaseline.ideographic, onlyReal: true);
3235 if (baselineI != null) {
3236 paint.color = const Color(0xFFFFD000);
3237 path = Path();
3238 path.moveTo(offset.dx, offset.dy + baselineI);
3239 path.lineTo(offset.dx + size.width, offset.dy + baselineI);
3240 context.canvas.drawPath(path, paint);
3241 }
3242 // alphabetic baseline
3243 final double? baselineA = getDistanceToBaseline(TextBaseline.alphabetic, onlyReal: true);
3244 if (baselineA != null) {
3245 paint.color = const Color(0xFF00FF00);
3246 path = Path();
3247 path.moveTo(offset.dx, offset.dy + baselineA);
3248 path.lineTo(offset.dx + size.width, offset.dy + baselineA);
3249 context.canvas.drawPath(path, paint);
3250 }
3251 return true;
3252 }());
3253 }
3254
3255 /// In debug mode, paints a rectangle if this render box has counted more
3256 /// pointer downs than pointer up events.
3257 ///
3258 /// Called for every [RenderBox] when [debugPaintPointersEnabled] is true.
3259 ///
3260 /// By default, events are not counted. For details on how to ensure that
3261 /// events are counted for your class, see [debugHandleEvent].
3262 @protected
3263 void debugPaintPointers(PaintingContext context, Offset offset) {
3264 assert(() {
3265 if (_debugActivePointers > 0) {
3266 final Paint paint = Paint()..color = Color(0x00BBBB | ((0x04000000 * depth) & 0xFF000000));
3267 context.canvas.drawRect(offset & size, paint);
3268 }
3269 return true;
3270 }());
3271 }
3272
3273 @override
3274 void debugFillProperties(DiagnosticPropertiesBuilder properties) {
3275 super.debugFillProperties(properties);
3276 properties.add(DiagnosticsProperty<Size>('size', _size, missingIfNull: true));
3277 }
3278}
3279
3280/// A mixin that provides useful default behaviors for boxes with children
3281/// managed by the [ContainerRenderObjectMixin] mixin.
3282///
3283/// By convention, this class doesn't override any members of the superclass.
3284/// Instead, it provides helpful functions that subclasses can call as
3285/// appropriate.
3286mixin RenderBoxContainerDefaultsMixin<
3287 ChildType extends RenderBox,
3288 ParentDataType extends ContainerBoxParentData<ChildType>
3289>
3290 implements ContainerRenderObjectMixin<ChildType, ParentDataType> {
3291 /// Returns the baseline of the first child with a baseline.
3292 ///
3293 /// Useful when the children are displayed vertically in the same order they
3294 /// appear in the child list.
3295 double? defaultComputeDistanceToFirstActualBaseline(TextBaseline baseline) {
3296 assert(!debugNeedsLayout);
3297 ChildType? child = firstChild;
3298 while (child != null) {
3299 final ParentDataType childParentData = child.parentData! as ParentDataType;
3300 final double? result = child.getDistanceToActualBaseline(baseline);
3301 if (result != null) {
3302 return result + childParentData.offset.dy;
3303 }
3304 child = childParentData.nextSibling;
3305 }
3306 return null;
3307 }
3308
3309 /// Returns the minimum baseline value among every child.
3310 ///
3311 /// Useful when the vertical position of the children isn't determined by the
3312 /// order in the child list.
3313 double? defaultComputeDistanceToHighestActualBaseline(TextBaseline baseline) {
3314 assert(!debugNeedsLayout);
3315 BaselineOffset minBaseline = BaselineOffset.noBaseline;
3316 ChildType? child = firstChild;
3317 while (child != null) {
3318 final ParentDataType childParentData = child.parentData! as ParentDataType;
3319 final BaselineOffset candidate =
3320 BaselineOffset(child.getDistanceToActualBaseline(baseline)) + childParentData.offset.dy;
3321 minBaseline = minBaseline.minOf(candidate);
3322 child = childParentData.nextSibling;
3323 }
3324 return minBaseline.offset;
3325 }
3326
3327 /// Performs a hit test on each child by walking the child list backwards.
3328 ///
3329 /// Stops walking once after the first child reports that it contains the
3330 /// given point. Returns whether any children contain the given point.
3331 ///
3332 /// See also:
3333 ///
3334 /// * [defaultPaint], which paints the children appropriate for this
3335 /// hit-testing strategy.
3336 bool defaultHitTestChildren(BoxHitTestResult result, {required Offset position}) {
3337 ChildType? child = lastChild;
3338 while (child != null) {
3339 // The x, y parameters have the top left of the node's box as the origin.
3340 final ParentDataType childParentData = child.parentData! as ParentDataType;
3341 final bool isHit = result.addWithPaintOffset(
3342 offset: childParentData.offset,
3343 position: position,
3344 hitTest: (BoxHitTestResult result, Offset transformed) {
3345 assert(transformed == position - childParentData.offset);
3346 return child!.hitTest(result, position: transformed);
3347 },
3348 );
3349 if (isHit) {
3350 return true;
3351 }
3352 child = childParentData.previousSibling;
3353 }
3354 return false;
3355 }
3356
3357 /// Paints each child by walking the child list forwards.
3358 ///
3359 /// See also:
3360 ///
3361 /// * [defaultHitTestChildren], which implements hit-testing of the children
3362 /// in a manner appropriate for this painting strategy.
3363 void defaultPaint(PaintingContext context, Offset offset) {
3364 ChildType? child = firstChild;
3365 while (child != null) {
3366 final ParentDataType childParentData = child.parentData! as ParentDataType;
3367 context.paintChild(child, childParentData.offset + offset);
3368 child = childParentData.nextSibling;
3369 }
3370 }
3371
3372 /// Returns a list containing the children of this render object.
3373 ///
3374 /// This function is useful when you need random-access to the children of
3375 /// this render object. If you're accessing the children in order, consider
3376 /// walking the child list directly.
3377 List<ChildType> getChildrenAsList() {
3378 final List<ChildType> result = <ChildType>[];
3379 RenderBox? child = firstChild;
3380 while (child != null) {
3381 final ParentDataType childParentData = child.parentData! as ParentDataType;
3382 result.add(child as ChildType);
3383 child = childParentData.nextSibling;
3384 }
3385 return result;
3386 }
3387}
3388