stack.dart 27.2 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4 5
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:math' as math;
6
import 'dart:ui' show lerpDouble;
7

8
import 'package:flutter/foundation.dart';
9

10
import 'box.dart';
11
import 'layer.dart';
12
import 'layout_helper.dart';
13
import 'object.dart';
14

Hixie's avatar
Hixie committed
15 16 17 18 19 20
/// An immutable 2D, axis-aligned, floating-point rectangle whose coordinates
/// are given relative to another rectangle's edges, known as the container.
/// Since the dimensions of the rectangle are relative to those of the
/// container, this class has no width and height members. To determine the
/// width or height of the rectangle, convert it to a [Rect] using [toRect()]
/// (passing the container's own Rect), and then examine that object.
Hixie's avatar
Hixie committed
21
///
22
/// The fields [left], [right], [bottom], and [top] must not be null.
23
@immutable
Hixie's avatar
Hixie committed
24 25
class RelativeRect {
  /// Creates a RelativeRect with the given values.
26 27
  ///
  /// The arguments must not be null.
28
  const RelativeRect.fromLTRB(this.left, this.top, this.right, this.bottom);
Hixie's avatar
Hixie committed
29 30 31 32 33

  /// Creates a RelativeRect from a Rect and a Size. The Rect (first argument)
  /// and the RelativeRect (the output) are in the coordinate space of the
  /// rectangle described by the Size, with 0,0 being at the top left.
  factory RelativeRect.fromSize(Rect rect, Size container) {
34
    return RelativeRect.fromLTRB(rect.left, rect.top, container.width - rect.right, container.height - rect.bottom);
Hixie's avatar
Hixie committed
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
  }

  /// Creates a RelativeRect from two Rects. The second Rect provides the
  /// container, the first provides the rectangle, in the same coordinate space,
  /// that is to be converted to a RelativeRect. The output will be in the
  /// container's coordinate space.
  ///
  /// For example, if the top left of the rect is at 0,0, and the top left of
  /// the container is at 100,100, then the top left of the output will be at
  /// -100,-100.
  ///
  /// If the first rect is actually in the container's coordinate space, then
  /// use [RelativeRect.fromSize] and pass the container's size as the second
  /// argument instead.
  factory RelativeRect.fromRect(Rect rect, Rect container) {
50
    return RelativeRect.fromLTRB(
Hixie's avatar
Hixie committed
51 52
      rect.left - container.left,
      rect.top - container.top,
53
      container.right - rect.right,
54
      container.bottom - rect.bottom,
Hixie's avatar
Hixie committed
55 56 57
    );
  }

58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
  /// Creates a RelativeRect from horizontal position using `start` and `end`
  /// rather than `left` and `right`.
  ///
  /// If `textDirection` is [TextDirection.rtl], then the `start` argument is
  /// used for the [right] property and the `end` argument is used for the
  /// [left] property. Otherwise, if `textDirection` is [TextDirection.ltr],
  /// then the `start` argument is used for the [left] property and the `end`
  /// argument is used for the [right] property.
  factory RelativeRect.fromDirectional({
    required TextDirection textDirection,
    required double start,
    required double top,
    required double end,
    required double bottom,
  }) {
    double left;
    double right;
    switch (textDirection) {
      case TextDirection.rtl:
        left = end;
        right = start;
      case TextDirection.ltr:
        left = start;
        right = end;
    }

    return RelativeRect.fromLTRB(left, top, right, bottom);
  }

87
  /// A rect that covers the entire container.
88
  static const RelativeRect fill = RelativeRect.fromLTRB(0.0, 0.0, 0.0, 0.0);
Hixie's avatar
Hixie committed
89 90

  /// Distance from the left side of the container to the left side of this rectangle.
91 92
  ///
  /// May be negative if the left side of the rectangle is outside of the container.
93
  final double left;
Hixie's avatar
Hixie committed
94 95

  /// Distance from the top side of the container to the top side of this rectangle.
96 97
  ///
  /// May be negative if the top side of the rectangle is outside of the container.
98
  final double top;
Hixie's avatar
Hixie committed
99 100

  /// Distance from the right side of the container to the right side of this rectangle.
101
  ///
102
  /// May be positive if the right side of the rectangle is outside of the container.
103
  final double right;
Hixie's avatar
Hixie committed
104 105

  /// Distance from the bottom side of the container to the bottom side of this rectangle.
106
  ///
107
  /// May be positive if the bottom side of the rectangle is outside of the container.
108
  final double bottom;
Hixie's avatar
Hixie committed
109

110 111 112 113 114 115
  /// Returns whether any of the values are greater than zero.
  ///
  /// This corresponds to one of the sides ([left], [top], [right], or [bottom]) having
  /// some positive inset towards the center.
  bool get hasInsets => left > 0.0 || top > 0.0 || right > 0.0 || bottom > 0.0;

Hixie's avatar
Hixie committed
116 117
  /// Returns a new rectangle object translated by the given offset.
  RelativeRect shift(Offset offset) {
118
    return RelativeRect.fromLTRB(left + offset.dx, top + offset.dy, right - offset.dx, bottom - offset.dy);
Hixie's avatar
Hixie committed
119 120 121 122
  }

  /// Returns a new rectangle with edges moved outwards by the given delta.
  RelativeRect inflate(double delta) {
123
    return RelativeRect.fromLTRB(left - delta, top - delta, right - delta, bottom - delta);
Hixie's avatar
Hixie committed
124 125 126 127 128 129 130 131 132
  }

  /// Returns a new rectangle with edges moved inwards by the given delta.
  RelativeRect deflate(double delta) {
    return inflate(-delta);
  }

  /// Returns a new rectangle that is the intersection of the given rectangle and this rectangle.
  RelativeRect intersect(RelativeRect other) {
133
    return RelativeRect.fromLTRB(
Hixie's avatar
Hixie committed
134 135 136
      math.max(left, other.left),
      math.max(top, other.top),
      math.max(right, other.right),
137
      math.max(bottom, other.bottom),
Hixie's avatar
Hixie committed
138 139 140
    );
  }

141
  /// Convert this [RelativeRect] to a [Rect], in the coordinate space of the container.
Ian Hickson's avatar
Ian Hickson committed
142 143 144 145 146
  ///
  /// See also:
  ///
  ///  * [toSize], which returns the size part of the rect, based on the size of
  ///    the container.
Hixie's avatar
Hixie committed
147
  Rect toRect(Rect container) {
148
    return Rect.fromLTRB(left, top, container.width - right, container.height - bottom);
Hixie's avatar
Hixie committed
149 150
  }

Ian Hickson's avatar
Ian Hickson committed
151 152 153 154 155 156
  /// Convert this [RelativeRect] to a [Size], assuming a container with the given size.
  ///
  /// See also:
  ///
  ///  * [toRect], which also computes the position relative to the container.
  Size toSize(Size container) {
157
    return Size(container.width - left - right, container.height - top - bottom);
Ian Hickson's avatar
Ian Hickson committed
158 159
  }

Hixie's avatar
Hixie committed
160 161 162
  /// Linearly interpolate between two RelativeRects.
  ///
  /// If either rect is null, this function interpolates from [RelativeRect.fill].
163
  ///
164
  /// {@macro dart.ui.shadow.lerp}
165
  static RelativeRect? lerp(RelativeRect? a, RelativeRect? b, double t) {
166 167
    if (identical(a, b)) {
      return a;
168 169
    }
    if (a == null) {
170
      return RelativeRect.fromLTRB(b!.left * t, b.top * t, b.right * t, b.bottom * t);
171
    }
Hixie's avatar
Hixie committed
172
    if (b == null) {
173
      final double k = 1.0 - t;
174
      return RelativeRect.fromLTRB(b!.left * k, b.top * k, b.right * k, b.bottom * k);
Hixie's avatar
Hixie committed
175
    }
176
    return RelativeRect.fromLTRB(
177 178 179 180
      lerpDouble(a.left, b.left, t)!,
      lerpDouble(a.top, b.top, t)!,
      lerpDouble(a.right, b.right, t)!,
      lerpDouble(a.bottom, b.bottom, t)!,
Hixie's avatar
Hixie committed
181 182 183
    );
  }

184
  @override
185
  bool operator ==(Object other) {
186
    if (identical(this, other)) {
Hixie's avatar
Hixie committed
187
      return true;
188
    }
189 190 191 192 193
    return other is RelativeRect
        && other.left == left
        && other.top == top
        && other.right == right
        && other.bottom == bottom;
Hixie's avatar
Hixie committed
194 195
  }

196
  @override
197
  int get hashCode => Object.hash(left, top, right, bottom);
Hixie's avatar
Hixie committed
198

199
  @override
200
  String toString() => 'RelativeRect.fromLTRB(${left.toStringAsFixed(1)}, ${top.toStringAsFixed(1)}, ${right.toStringAsFixed(1)}, ${bottom.toStringAsFixed(1)})';
Hixie's avatar
Hixie committed
201 202
}

Adam Barth's avatar
Adam Barth committed
203
/// Parent data for use with [RenderStack].
204
class StackParentData extends ContainerBoxParentData<RenderBox> {
Hixie's avatar
Hixie committed
205
  /// The distance by which the child's top edge is inset from the top of the stack.
206
  double? top;
207

Hixie's avatar
Hixie committed
208
  /// The distance by which the child's right edge is inset from the right of the stack.
209
  double? right;
210

Hixie's avatar
Hixie committed
211
  /// The distance by which the child's bottom edge is inset from the bottom of the stack.
212
  double? bottom;
213

Hixie's avatar
Hixie committed
214
  /// The distance by which the child's left edge is inset from the left of the stack.
215
  double? left;
216

217 218 219
  /// The child's width.
  ///
  /// Ignored if both left and right are non-null.
220
  double? width;
221 222 223 224

  /// The child's height.
  ///
  /// Ignored if both top and bottom are non-null.
225
  double? height;
226

Hixie's avatar
Hixie committed
227
  /// Get or set the current values in terms of a RelativeRect object.
228
  RelativeRect get rect => RelativeRect.fromLTRB(left!, top!, right!, bottom!);
229
  set rect(RelativeRect value) {
Hixie's avatar
Hixie committed
230 231 232
    top = value.top;
    right = value.right;
    bottom = value.bottom;
Hixie's avatar
Hixie committed
233
    left = value.left;
Hixie's avatar
Hixie committed
234 235
  }

Hixie's avatar
Hixie committed
236
  /// Whether this child is considered positioned.
237
  ///
Hixie's avatar
Hixie committed
238
  /// A child is positioned if any of the top, right, bottom, or left properties
239 240 241
  /// are non-null. Positioned children do not factor into determining the size
  /// of the stack but are instead placed relative to the non-positioned
  /// children in the stack.
242
  bool get isPositioned => top != null || right != null || bottom != null || left != null || width != null || height != null;
243

244
  @override
Hixie's avatar
Hixie committed
245
  String toString() {
246 247 248 249 250 251 252 253
    final List<String> values = <String>[
      if (top != null) 'top=${debugFormatDouble(top)}',
      if (right != null) 'right=${debugFormatDouble(right)}',
      if (bottom != null) 'bottom=${debugFormatDouble(bottom)}',
      if (left != null) 'left=${debugFormatDouble(left)}',
      if (width != null) 'width=${debugFormatDouble(width)}',
      if (height != null) 'height=${debugFormatDouble(height)}',
    ];
254
    if (values.isEmpty) {
255
      values.add('not positioned');
256
    }
257
    values.add(super.toString());
Hixie's avatar
Hixie committed
258 259
    return values.join('; ');
  }
260 261
}

262 263
/// How to size the non-positioned children of a [Stack].
///
264
/// This enum is used with [Stack.fit] and [RenderStack.fit] to control
265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303
/// how the [BoxConstraints] passed from the stack's parent to the stack's child
/// are adjusted.
///
/// See also:
///
///  * [Stack], the widget that uses this.
///  * [RenderStack], the render object that implements the stack algorithm.
enum StackFit {
  /// The constraints passed to the stack from its parent are loosened.
  ///
  /// For example, if the stack has constraints that force it to 350x600, then
  /// this would allow the non-positioned children of the stack to have any
  /// width from zero to 350 and any height from zero to 600.
  ///
  /// See also:
  ///
  ///  * [Center], which loosens the constraints passed to its child and then
  ///    centers the child in itself.
  ///  * [BoxConstraints.loosen], which implements the loosening of box
  ///    constraints.
  loose,

  /// The constraints passed to the stack from its parent are tightened to the
  /// biggest size allowed.
  ///
  /// For example, if the stack has loose constraints with a width in the range
  /// 10 to 100 and a height in the range 0 to 600, then the non-positioned
  /// children of the stack would all be sized as 100 pixels wide and 600 high.
  expand,

  /// The constraints passed to the stack from its parent are passed unmodified
  /// to the non-positioned children.
  ///
  /// For example, if a [Stack] is an [Expanded] child of a [Row], the
  /// horizontal constraints will be tight and the vertical constraints will be
  /// loose.
  passthrough,
}

304
/// Implements the stack layout algorithm.
305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340
///
/// In a stack layout, the children are positioned on top of each other in the
/// order in which they appear in the child list. First, the non-positioned
/// children (those with null values for top, right, bottom, and left) are
/// laid out and initially placed in the upper-left corner of the stack. The
/// stack is then sized to enclose all of the non-positioned children. If there
/// are no non-positioned children, the stack becomes as large as possible.
///
/// The final location of non-positioned children is determined by the alignment
/// parameter. The left of each non-positioned child becomes the
/// difference between the child's width and the stack's width scaled by
/// alignment.x. The top of each non-positioned child is computed
/// similarly and scaled by alignment.y. So if the alignment x and y properties
/// are 0.0 (the default) then the non-positioned children remain in the
/// upper-left corner. If the alignment x and y properties are 0.5 then the
/// non-positioned children are centered within the stack.
///
/// Next, the positioned children are laid out. If a child has top and bottom
/// values that are both non-null, the child is given a fixed height determined
/// by subtracting the sum of the top and bottom values from the height of the stack.
/// Similarly, if the child has right and left values that are both non-null,
/// the child is given a fixed width derived from the stack's width.
/// Otherwise, the child is given unbounded constraints in the non-fixed dimensions.
///
/// Once the child is laid out, the stack positions the child
/// according to the top, right, bottom, and left properties of their
/// [StackParentData]. For example, if the bottom value is 10.0, the
/// bottom edge of the child will be inset 10.0 pixels from the bottom
/// edge of the stack. If the child extends beyond the bounds of the
/// stack, the stack will clip the child's painting to the bounds of
/// the stack.
///
/// See also:
///
///  * [RenderFlow]
class RenderStack extends RenderBox
Hans Muller's avatar
Hans Muller committed
341 342
    with ContainerRenderObjectMixin<RenderBox, StackParentData>,
         RenderBoxContainerDefaultsMixin<RenderBox, StackParentData> {
343 344 345 346 347
  /// Creates a stack render object.
  ///
  /// By default, the non-positioned children of the stack are aligned by their
  /// top left corners.
  RenderStack({
348
    List<RenderBox>? children,
349
    AlignmentGeometry alignment = AlignmentDirectional.topStart,
350
    TextDirection? textDirection,
351
    StackFit fit = StackFit.loose,
352
    Clip clipBehavior = Clip.hardEdge,
353
  }) : _alignment = alignment,
354
       _textDirection = textDirection,
355
       _fit = fit,
356
       _clipBehavior = clipBehavior {
357 358 359
    addAll(children);
  }

360 361
  bool _hasVisualOverflow = false;

362
  @override
363
  void setupParentData(RenderBox child) {
364
    if (child.parentData is! StackParentData) {
365
      child.parentData = StackParentData();
366
    }
367 368
  }

369
  Alignment? _resolvedAlignment;
370

Ian Hickson's avatar
Ian Hickson committed
371
  void _resolve() {
372
    if (_resolvedAlignment != null) {
Ian Hickson's avatar
Ian Hickson committed
373
      return;
374
    }
Ian Hickson's avatar
Ian Hickson committed
375 376 377 378 379 380
    _resolvedAlignment = alignment.resolve(textDirection);
  }

  void _markNeedResolution() {
    _resolvedAlignment = null;
    markNeedsLayout();
381 382
  }

383 384
  /// How to align the non-positioned or partially-positioned children in the
  /// stack.
385 386 387
  ///
  /// The non-positioned children are placed relative to each other such that
  /// the points determined by [alignment] are co-located. For example, if the
388
  /// [alignment] is [Alignment.topLeft], then the top left corner of
389
  /// each non-positioned child will be located at the same global coordinate.
Ian Hickson's avatar
Ian Hickson committed
390
  ///
391 392 393 394 395 396
  /// Partially-positioned children, those that do not specify an alignment in a
  /// particular axis (e.g. that have neither `top` nor `bottom` set), use the
  /// alignment to determine how they should be positioned in that
  /// under-specified axis.
  ///
  /// If this is set to an [AlignmentDirectional] object, then [textDirection]
397 398 399 400
  /// must not be null.
  AlignmentGeometry get alignment => _alignment;
  AlignmentGeometry _alignment;
  set alignment(AlignmentGeometry value) {
401
    if (_alignment == value) {
Ian Hickson's avatar
Ian Hickson committed
402
      return;
403
    }
Ian Hickson's avatar
Ian Hickson committed
404 405
    _alignment = value;
    _markNeedResolution();
406 407 408
  }

  /// The text direction with which to resolve [alignment].
Ian Hickson's avatar
Ian Hickson committed
409 410 411
  ///
  /// This may be changed to null, but only after the [alignment] has been changed
  /// to a value that does not depend on the direction.
412 413 414
  TextDirection? get textDirection => _textDirection;
  TextDirection? _textDirection;
  set textDirection(TextDirection? value) {
415
    if (_textDirection == value) {
Ian Hickson's avatar
Ian Hickson committed
416
      return;
417
    }
Ian Hickson's avatar
Ian Hickson committed
418 419
    _textDirection = value;
    _markNeedResolution();
Hans Muller's avatar
Hans Muller committed
420 421
  }

422 423 424 425 426
  /// How to size the non-positioned children in the stack.
  ///
  /// The constraints passed into the [RenderStack] from its parent are either
  /// loosened ([StackFit.loose]) or tightened to their biggest size
  /// ([StackFit.expand]).
427 428 429 430 431
  StackFit get fit => _fit;
  StackFit _fit;
  set fit(StackFit value) {
    if (_fit != value) {
      _fit = value;
432 433 434 435
      markNeedsLayout();
    }
  }

436
  /// {@macro flutter.material.Material.clipBehavior}
437
  ///
438 439 440 441 442 443 444 445 446 447
  /// Stacks only clip children whose geometry overflow the stack. A child that
  /// paints outside its bounds (e.g. a box with a shadow) will not be clipped,
  /// regardless of the value of this property. Similarly, a child that itself
  /// has a descendant that overflows the stack will not be clipped, as only the
  /// geometry of the stack's direct children are considered.
  ///
  /// To clip children whose geometry does not overflow the stack, consider
  /// using a [RenderClipRect] render object.
  ///
  /// Defaults to [Clip.hardEdge].
448 449 450 451 452
  Clip get clipBehavior => _clipBehavior;
  Clip _clipBehavior = Clip.hardEdge;
  set clipBehavior(Clip value) {
    if (value != _clipBehavior) {
      _clipBehavior = value;
453
      markNeedsPaint();
454
      markNeedsSemanticsUpdate();
455 456 457
    }
  }

458
  /// Helper function for calculating the intrinsics metrics of a Stack.
459
  static double getIntrinsicDimension(RenderBox? firstChild, double Function(RenderBox child) mainChildSizeGetter) {
460
    double extent = 0.0;
461
    RenderBox? child = firstChild;
462
    while (child != null) {
463
      final StackParentData childParentData = child.parentData! as StackParentData;
464
      if (!childParentData.isPositioned) {
465
        extent = math.max(extent, mainChildSizeGetter(child));
466
      }
Hixie's avatar
Hixie committed
467 468
      assert(child.parentData == childParentData);
      child = childParentData.nextSibling;
469
    }
470
    return extent;
471 472
  }

473
  @override
474
  double computeMinIntrinsicWidth(double height) {
475
    return getIntrinsicDimension(firstChild, (RenderBox child) => child.getMinIntrinsicWidth(height));
476 477
  }

478
  @override
479
  double computeMaxIntrinsicWidth(double height) {
480
    return getIntrinsicDimension(firstChild, (RenderBox child) => child.getMaxIntrinsicWidth(height));
481 482
  }

483
  @override
484
  double computeMinIntrinsicHeight(double width) {
485
    return getIntrinsicDimension(firstChild, (RenderBox child) => child.getMinIntrinsicHeight(width));
486 487 488
  }

  @override
489
  double computeMaxIntrinsicHeight(double width) {
490
    return getIntrinsicDimension(firstChild, (RenderBox child) => child.getMaxIntrinsicHeight(width));
491 492
  }

493
  @override
494
  double? computeDistanceToActualBaseline(TextBaseline baseline) {
495 496 497
    return defaultComputeDistanceToHighestActualBaseline(baseline);
  }

498 499 500 501 502 503 504 505 506 507
  /// Lays out the positioned `child` according to `alignment` within a Stack of `size`.
  ///
  /// Returns true when the child has visual overflow.
  static bool layoutPositionedChild(RenderBox child, StackParentData childParentData, Size size, Alignment alignment) {
    assert(childParentData.isPositioned);
    assert(child.parentData == childParentData);

    bool hasVisualOverflow = false;
    BoxConstraints childConstraints = const BoxConstraints();

508
    if (childParentData.left != null && childParentData.right != null) {
509
      childConstraints = childConstraints.tighten(width: size.width - childParentData.right! - childParentData.left!);
510
    } else if (childParentData.width != null) {
511
      childConstraints = childConstraints.tighten(width: childParentData.width);
512
    }
513

514
    if (childParentData.top != null && childParentData.bottom != null) {
515
      childConstraints = childConstraints.tighten(height: size.height - childParentData.bottom! - childParentData.top!);
516
    } else if (childParentData.height != null) {
517
      childConstraints = childConstraints.tighten(height: childParentData.height);
518
    }
519 520 521

    child.layout(childConstraints, parentUsesSize: true);

522
    final double x;
523
    if (childParentData.left != null) {
524
      x = childParentData.left!;
525
    } else if (childParentData.right != null) {
526
      x = size.width - childParentData.right! - child.size.width;
527 528 529 530
    } else {
      x = alignment.alongOffset(size - child.size as Offset).dx;
    }

531
    if (x < 0.0 || x + child.size.width > size.width) {
532
      hasVisualOverflow = true;
533
    }
534

535
    final double y;
536
    if (childParentData.top != null) {
537
      y = childParentData.top!;
538
    } else if (childParentData.bottom != null) {
539
      y = size.height - childParentData.bottom! - child.size.height;
540 541 542 543
    } else {
      y = alignment.alongOffset(size - child.size as Offset).dy;
    }

544
    if (y < 0.0 || y + child.size.height > size.height) {
545
      hasVisualOverflow = true;
546
    }
547 548 549 550 551 552

    childParentData.offset = Offset(x, y);

    return hasVisualOverflow;
  }

553
  @override
554 555 556 557 558 559 560 561
  Size computeDryLayout(BoxConstraints constraints) {
    return _computeSize(
      constraints: constraints,
      layoutChild: ChildLayoutHelper.dryLayoutChild,
    );
  }

  Size _computeSize({required BoxConstraints constraints, required ChildLayouter layoutChild}) {
Ian Hickson's avatar
Ian Hickson committed
562 563
    _resolve();
    assert(_resolvedAlignment != null);
564
    bool hasNonPositionedChildren = false;
565
    if (childCount == 0) {
566
      return (constraints.biggest.isFinite) ? constraints.biggest : constraints.smallest;
567
    }
568

569 570 571
    double width = constraints.minWidth;
    double height = constraints.minHeight;

572
    final BoxConstraints nonPositionedConstraints;
573
    switch (fit) {
574 575 576
      case StackFit.loose:
        nonPositionedConstraints = constraints.loosen();
      case StackFit.expand:
577
        nonPositionedConstraints = BoxConstraints.tight(constraints.biggest);
578 579 580
      case StackFit.passthrough:
        nonPositionedConstraints = constraints;
    }
581

582
    RenderBox? child = firstChild;
583
    while (child != null) {
584
      final StackParentData childParentData = child.parentData! as StackParentData;
585

Hixie's avatar
Hixie committed
586
      if (!childParentData.isPositioned) {
587 588
        hasNonPositionedChildren = true;

589
        final Size childSize = layoutChild(child, nonPositionedConstraints);
590 591 592 593 594

        width = math.max(width, childSize.width);
        height = math.max(height, childSize.height);
      }

Hixie's avatar
Hixie committed
595
      child = childParentData.nextSibling;
596 597
    }

598
    final Size size;
599
    if (hasNonPositionedChildren) {
600
      size = Size(width, height);
601 602 603
      assert(size.width == constraints.constrainWidth(width));
      assert(size.height == constraints.constrainHeight(height));
    } else {
604
      size = constraints.biggest;
605
    }
606

607
    assert(size.isFinite);
608 609
    return size;
  }
610

611 612 613 614 615 616 617 618 619 620 621 622
  @override
  void performLayout() {
    final BoxConstraints constraints = this.constraints;
    _hasVisualOverflow = false;

    size = _computeSize(
      constraints: constraints,
      layoutChild: ChildLayoutHelper.layoutChild,
    );

    assert(_resolvedAlignment != null);
    RenderBox? child = firstChild;
623
    while (child != null) {
624
      final StackParentData childParentData = child.parentData! as StackParentData;
625

Hixie's avatar
Hixie committed
626
      if (!childParentData.isPositioned) {
627
        childParentData.offset = _resolvedAlignment!.alongOffset(size - child.size as Offset);
Hans Muller's avatar
Hans Muller committed
628
      } else {
629
        _hasVisualOverflow = layoutPositionedChild(child, childParentData, size, _resolvedAlignment!) || _hasVisualOverflow;
630 631
      }

Hixie's avatar
Hixie committed
632 633
      assert(child.parentData == childParentData);
      child = childParentData.nextSibling;
634 635 636
    }
  }

637
  @override
638
  bool hitTestChildren(BoxHitTestResult result, { required Offset position }) {
Adam Barth's avatar
Adam Barth committed
639
    return defaultHitTestChildren(result, position: position);
640 641
  }

642 643 644 645 646 647 648 649
  /// Override in subclasses to customize how the stack paints.
  ///
  /// By default, the stack uses [defaultPaint]. This function is called by
  /// [paint] after potentially applying a clip to contain visual overflow.
  @protected
  void paintStack(PaintingContext context, Offset offset) {
    defaultPaint(context, offset);
  }
Hans Muller's avatar
Hans Muller committed
650

651
  @override
652
  void paint(PaintingContext context, Offset offset) {
653
    if (clipBehavior != Clip.none && _hasVisualOverflow) {
654
      _clipRectLayer.layer = context.pushClipRect(
655 656 657 658 659
        needsCompositing,
        offset,
        Offset.zero & size,
        paintStack,
        clipBehavior: clipBehavior,
660
        oldLayer: _clipRectLayer.layer,
661
      );
662
    } else {
663
      _clipRectLayer.layer = null;
Hans Muller's avatar
Hans Muller committed
664
      paintStack(context, offset);
665
    }
666
  }
Hixie's avatar
Hixie committed
667

668 669 670 671 672 673 674
  final LayerHandle<ClipRectLayer> _clipRectLayer = LayerHandle<ClipRectLayer>();

  @override
  void dispose() {
    _clipRectLayer.layer = null;
    super.dispose();
  }
675

676
  @override
677 678 679 680 681 682 683 684 685 686
  Rect? describeApproximatePaintClip(RenderObject child) {
    switch (clipBehavior) {
      case Clip.none:
        return null;
      case Clip.hardEdge:
      case Clip.antiAlias:
      case Clip.antiAliasWithSaveLayer:
        return _hasVisualOverflow ? Offset.zero & size : null;
    }
  }
Adam Barth's avatar
Adam Barth committed
687 688

  @override
689 690
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
691 692 693
    properties.add(DiagnosticsProperty<AlignmentGeometry>('alignment', alignment));
    properties.add(EnumProperty<TextDirection>('textDirection', textDirection));
    properties.add(EnumProperty<StackFit>('fit', fit));
694
    properties.add(EnumProperty<Clip>('clipBehavior', clipBehavior, defaultValue: Clip.hardEdge));
Adam Barth's avatar
Adam Barth committed
695
  }
696
}
Hans Muller's avatar
Hans Muller committed
697 698 699

/// Implements the same layout algorithm as RenderStack but only paints the child
/// specified by index.
700 701
///
/// Although only one child is displayed, the cost of the layout algorithm is
Hans Muller's avatar
Hans Muller committed
702
/// still O(N), like an ordinary stack.
703 704 705
class RenderIndexedStack extends RenderStack {
  /// Creates a stack render object that paints a single child.
  ///
706
  /// If the [index] parameter is null, nothing is displayed.
Hans Muller's avatar
Hans Muller committed
707
  RenderIndexedStack({
708 709 710
    super.children,
    super.alignment,
    super.textDirection,
711 712
    super.fit,
    super.clipBehavior,
713
    int? index = 0,
714
  }) : _index = index;
Hans Muller's avatar
Hans Muller committed
715

716 717
  @override
  void visitChildrenForSemantics(RenderObjectVisitor visitor) {
718
    if (index != null && firstChild != null) {
719
      visitor(_childAtIndex());
720
    }
721 722
  }

723
  /// The index of the child to show, null if nothing is to be displayed.
724 725 726
  int? get index => _index;
  int? _index;
  set index(int? value) {
Hans Muller's avatar
Hans Muller committed
727 728 729 730 731 732 733
    if (_index != value) {
      _index = value;
      markNeedsLayout();
    }
  }

  RenderBox _childAtIndex() {
734
    assert(index != null);
735
    RenderBox? child = firstChild;
Hans Muller's avatar
Hans Muller committed
736
    int i = 0;
737
    while (child != null && i < index!) {
738
      final StackParentData childParentData = child.parentData! as StackParentData;
Hixie's avatar
Hixie committed
739
      child = childParentData.nextSibling;
Hans Muller's avatar
Hans Muller committed
740 741 742 743
      i += 1;
    }
    assert(i == index);
    assert(child != null);
744
    return child!;
Hans Muller's avatar
Hans Muller committed
745 746
  }

747
  @override
748
  bool hitTestChildren(BoxHitTestResult result, { required Offset position }) {
749
    if (firstChild == null || index == null) {
Adam Barth's avatar
Adam Barth committed
750
      return false;
751
    }
752
    final RenderBox child = _childAtIndex();
753
    final StackParentData childParentData = child.parentData! as StackParentData;
754 755 756
    return result.addWithPaintOffset(
      offset: childParentData.offset,
      position: position,
757
      hitTest: (BoxHitTestResult result, Offset transformed) {
758
        assert(transformed == position - childParentData.offset);
759
        return child.hitTest(result, position: transformed);
760 761
      },
    );
Hans Muller's avatar
Hans Muller committed
762 763
  }

764
  @override
Hans Muller's avatar
Hans Muller committed
765
  void paintStack(PaintingContext context, Offset offset) {
766
    if (firstChild == null || index == null) {
Hans Muller's avatar
Hans Muller committed
767
      return;
768
    }
769
    final RenderBox child = _childAtIndex();
770
    final StackParentData childParentData = child.parentData! as StackParentData;
Adam Barth's avatar
Adam Barth committed
771
    context.paintChild(child, childParentData.offset + offset);
Hans Muller's avatar
Hans Muller committed
772
  }
Adam Barth's avatar
Adam Barth committed
773 774

  @override
775 776
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
777
    properties.add(IntProperty('index', index));
Adam Barth's avatar
Adam Barth committed
778
  }
779 780 781 782 783 784 785 786 787

  @override
  List<DiagnosticsNode> debugDescribeChildren() {
    final List<DiagnosticsNode> children = <DiagnosticsNode>[];
    int i = 0;
    RenderObject? child = firstChild;
    while (child != null) {
      children.add(child.toDiagnosticsNode(
        name: 'child ${i + 1}',
788
        style: i != index ? DiagnosticsTreeStyle.offstage : null,
789 790 791 792 793 794
      ));
      child = (child.parentData! as StackParentData).nextSibling;
      i += 1;
    }
    return children;
  }
Hans Muller's avatar
Hans Muller committed
795
}