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

5
import 'dart:async';
6
import 'dart:collection';
7
import 'dart:math' as math;
8

9
import 'package:flutter/foundation.dart';
10
import 'package:flutter/rendering.dart';
11
import 'package:flutter/scheduler.dart';
12

13 14
import 'basic.dart';
import 'framework.dart';
15
import 'ticker_provider.dart';
16

17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
/// A place in an [Overlay] that can contain a widget.
///
/// Overlay entries are inserted into an [Overlay] using the
/// [OverlayState.insert] or [OverlayState.insertAll] functions. To find the
/// closest enclosing overlay for a given [BuildContext], use the [Overlay.of]
/// function.
///
/// An overlay entry can be in at most one overlay at a time. To remove an entry
/// from its overlay, call the [remove] function on the overlay entry.
///
/// Because an [Overlay] uses a [Stack] layout, overlay entries can use
/// [Positioned] and [AnimatedPositioned] to position themselves within the
/// overlay.
///
/// For example, [Draggable] uses an [OverlayEntry] to show the drag avatar that
/// follows the user's finger across the screen after the drag begins. Using the
/// overlay to display the drag avatar lets the avatar float over the other
/// widgets in the app. As the user's finger moves, draggable calls
/// [markNeedsBuild] on the overlay entry to cause it to rebuild. It its build,
/// the entry includes a [Positioned] with its top and left property set to
/// position the drag avatar near the user's finger. When the drag is over,
/// [Draggable] removes the entry from the overlay to remove the drag avatar
/// from view.
///
41 42 43 44 45 46
/// By default, if there is an entirely [opaque] entry over this one, then this
/// one will not be included in the widget tree (in particular, stateful widgets
/// within the overlay entry will not be instantiated). To ensure that your
/// overlay entry is still built even if it is not visible, set [maintainState]
/// to true. This is more expensive, so should be done with care. In particular,
/// if widgets in an overlay entry with [maintainState] set to true repeatedly
47
/// call [State.setState], the user's battery will be drained unnecessarily.
48
///
49 50
/// See also:
///
51 52 53 54
///  * [Overlay]
///  * [OverlayState]
///  * [WidgetsApp]
///  * [MaterialApp]
55
class OverlayEntry {
56 57 58 59 60
  /// Creates an overlay entry.
  ///
  /// To insert the entry into an [Overlay], first find the overlay using
  /// [Overlay.of] and then call [OverlayState.insert]. To remove the entry,
  /// call [remove] on the overlay entry itself.
61
  OverlayEntry({
62
    @required this.builder,
63 64
    bool opaque = false,
    bool maintainState = false,
65 66 67 68 69
  }) : assert(builder != null),
       assert(opaque != null),
       assert(maintainState != null),
       _opaque = opaque,
       _maintainState = maintainState;
70

71 72
  /// This entry will include the widget built by this builder in the overlay at
  /// the entry's position.
73
  ///
74
  /// To cause this builder to be called again, call [markNeedsBuild] on this
75
  /// overlay entry.
76
  final WidgetBuilder builder;
77

78 79
  /// Whether this entry occludes the entire overlay.
  ///
80 81 82
  /// If an entry claims to be opaque, then, for efficiency, the overlay will
  /// skip building entries below that entry unless they have [maintainState]
  /// set.
83 84
  bool get opaque => _opaque;
  bool _opaque;
85
  set opaque(bool value) {
Adam Barth's avatar
Adam Barth committed
86
    if (_opaque == value)
87
      return;
88
    _opaque = value;
89
    _overlay?._didChangeEntryOpacity();
90 91
  }

92 93 94 95 96 97 98 99 100
  /// Whether this entry must be included in the tree even if there is a fully
  /// [opaque] entry above it.
  ///
  /// By default, if there is an entirely [opaque] entry over this one, then this
  /// one will not be included in the widget tree (in particular, stateful widgets
  /// within the overlay entry will not be instantiated). To ensure that your
  /// overlay entry is still built even if it is not visible, set [maintainState]
  /// to true. This is more expensive, so should be done with care. In particular,
  /// if widgets in an overlay entry with [maintainState] set to true repeatedly
101
  /// call [State.setState], the user's battery will be drained unnecessarily.
102 103 104 105 106 107
  ///
  /// This is used by the [Navigator] and [Route] objects to ensure that routes
  /// are kept around even when in the background, so that [Future]s promised
  /// from subsequent routes will be handled properly when they complete.
  bool get maintainState => _maintainState;
  bool _maintainState;
108
  set maintainState(bool value) {
109 110 111 112 113 114 115 116
    assert(_maintainState != null);
    if (_maintainState == value)
      return;
    _maintainState = value;
    assert(_overlay != null);
    _overlay._didChangeEntryOpacity();
  }

117
  OverlayState _overlay;
118
  final GlobalKey<_OverlayEntryWidgetState> _key = GlobalKey<_OverlayEntryWidgetState>();
119

120
  /// Remove this entry from the overlay.
121 122 123 124
  ///
  /// This should only be called once.
  ///
  /// If this method is called while the [SchedulerBinding.schedulerPhase] is
125 126
  /// [SchedulerPhase.persistentCallbacks], i.e. during the build, layout, or
  /// paint phases (see [WidgetsBinding.drawFrame]), then the removal is
127 128 129 130
  /// delayed until the post-frame callbacks phase. Otherwise the removal is
  /// done synchronously. This means that it is safe to call during builds, but
  /// also that if you do call this during a build, the UI will not update until
  /// the next frame (i.e. many milliseconds later).
131
  void remove() {
132
    assert(_overlay != null);
133
    final OverlayState overlay = _overlay;
134
    _overlay = null;
135 136 137 138 139 140 141
    if (SchedulerBinding.instance.schedulerPhase == SchedulerPhase.persistentCallbacks) {
      SchedulerBinding.instance.addPostFrameCallback((Duration duration) {
        overlay._remove(this);
      });
    } else {
      overlay._remove(this);
    }
142
  }
143

144 145 146
  /// Cause this entry to rebuild during the next pipeline flush.
  ///
  /// You need to call this function if the output of [builder] has changed.
147
  void markNeedsBuild() {
148
    _key.currentState?._markNeedsBuild();
149
  }
150

151
  @override
152
  String toString() => '${describeIdentity(this)}(opaque: $opaque; maintainState: $maintainState)';
153 154
}

155 156 157 158 159 160 161 162 163
class _OverlayEntryWidget extends StatefulWidget {
  const _OverlayEntryWidget({
    @required Key key,
    @required this.entry,
    this.tickerEnabled = true,
  }) : assert(key != null),
       assert(entry != null),
       assert(tickerEnabled != null),
       super(key: key);
164

165
  final OverlayEntry entry;
166
  final bool tickerEnabled;
167 168

  @override
169
  _OverlayEntryWidgetState createState() => _OverlayEntryWidgetState();
170
}
171

172
class _OverlayEntryWidgetState extends State<_OverlayEntryWidget> {
173
  @override
174
  Widget build(BuildContext context) {
175 176 177 178
    return TickerMode(
      enabled: widget.tickerEnabled,
      child: widget.entry.builder(context),
    );
179
  }
180 181 182 183

  void _markNeedsBuild() {
    setState(() { /* the state that changed is in the builder */ });
  }
184 185
}

186
/// A [Stack] of entries that can be managed independently.
187 188 189 190 191 192 193 194 195 196 197 198
///
/// Overlays let independent child widgets "float" visual elements on top of
/// other widgets by inserting them into the overlay's [Stack]. The overlay lets
/// each of these widgets manage their participation in the overlay using
/// [OverlayEntry] objects.
///
/// Although you can create an [Overlay] directly, it's most common to use the
/// overlay created by the [Navigator] in a [WidgetsApp] or a [MaterialApp]. The
/// navigator uses its overlay to manage the visual appearance of its routes.
///
/// See also:
///
199 200 201 202
///  * [OverlayEntry].
///  * [OverlayState].
///  * [WidgetsApp].
///  * [MaterialApp].
203
class Overlay extends StatefulWidget {
204 205 206 207 208
  /// Creates an overlay.
  ///
  /// The initial entries will be inserted into the overlay when its associated
  /// [OverlayState] is initialized.
  ///
209 210
  /// Rather than creating an overlay, consider using the overlay that is
  /// created by the [WidgetsApp] or the [MaterialApp] for the application.
211
  const Overlay({
212
    Key key,
213
    this.initialEntries = const <OverlayEntry>[],
214 215
  }) : assert(initialEntries != null),
       super(key: key);
216

217
  /// The entries to include in the overlay initially.
218 219 220 221 222 223 224 225
  ///
  /// These entries are only used when the [OverlayState] is initialized. If you
  /// are providing a new [Overlay] description for an overlay that's already in
  /// the tree, then the new entries are ignored.
  ///
  /// To add entries to an [Overlay] that is already in the tree, use
  /// [Overlay.of] to obtain the [OverlayState] (or assign a [GlobalKey] to the
  /// [Overlay] widget and obtain the [OverlayState] via
226 227
  /// [GlobalKey.currentState]), and then use [OverlayState.insert] or
  /// [OverlayState.insertAll].
228 229
  ///
  /// To remove an entry from an [Overlay], use [OverlayEntry.remove].
230 231
  final List<OverlayEntry> initialEntries;

232
  /// The state from the closest instance of this class that encloses the given context.
233
  ///
234
  /// In debug mode, if the `debugRequiredFor` argument is provided then this
235 236
  /// function will assert that an overlay was found and will throw an exception
  /// if not. The exception attempts to explain that the calling [Widget] (the
237
  /// one given by the `debugRequiredFor` argument) needs an [Overlay] to be
238
  /// present to function.
239 240 241 242 243 244
  ///
  /// Typical usage is as follows:
  ///
  /// ```dart
  /// OverlayState overlay = Overlay.of(context);
  /// ```
245 246 247 248 249 250 251 252 253 254 255 256
  ///
  /// If `rootOverlay` is set to true, the state from the furthest instance of
  /// this class is given instead. Useful for installing overlay entries
  /// above all subsequent instances of [Overlay].
  static OverlayState of(
    BuildContext context, {
    bool rootOverlay = false,
    Widget debugRequiredFor,
  }) {
    final OverlayState result = rootOverlay
        ? context.findRootAncestorStateOfType<OverlayState>()
        : context.findAncestorStateOfType<OverlayState>();
257 258
    assert(() {
      if (debugRequiredFor != null && result == null) {
259 260 261 262 263 264 265 266 267 268
        final List<DiagnosticsNode> information = <DiagnosticsNode>[
          ErrorSummary('No Overlay widget found.'),
          ErrorDescription('${debugRequiredFor.runtimeType} widgets require an Overlay widget ancestor for correct operation.'),
          ErrorHint('The most common way to add an Overlay to an application is to include a MaterialApp or Navigator widget in the runApp() call.'),
          DiagnosticsProperty<Widget>('The specific widget that failed to find an overlay was', debugRequiredFor, style: DiagnosticsTreeStyle.errorProperty),
          if (context.widget != debugRequiredFor)
            context.describeElement('The context from which that widget was searching for an overlay was')
        ];

        throw FlutterError.fromParts(information);
269 270
      }
      return true;
271
    }());
272 273
    return result;
  }
Hixie's avatar
Hixie committed
274

275
  @override
276
  OverlayState createState() => OverlayState();
277 278
}

279
/// The current state of an [Overlay].
280 281 282
///
/// Used to insert [OverlayEntry]s into the overlay using the [insert] and
/// [insertAll] functions.
283
class OverlayState extends State<Overlay> with TickerProviderStateMixin {
284
  final List<OverlayEntry> _entries = <OverlayEntry>[];
285

286
  @override
287 288
  void initState() {
    super.initState();
289
    insertAll(widget.initialEntries);
290 291
  }

292 293 294 295 296 297 298 299 300
  int _insertionIndex(OverlayEntry below, OverlayEntry above) {
    assert(above == null || below == null);
    if (below != null)
      return _entries.indexOf(below);
    if (above != null)
      return _entries.indexOf(above) + 1;
    return _entries.length;
  }

301 302
  /// Insert the given entry into the overlay.
  ///
303
  /// If `below` is non-null, the entry is inserted just below `below`.
304
  /// If `above` is non-null, the entry is inserted just above `above`.
305
  /// Otherwise, the entry is inserted on top.
306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322
  ///
  /// It is an error to specify both `above` and `below`.
  void insert(OverlayEntry entry, { OverlayEntry below, OverlayEntry above }) {
    assert(
      above == null || below == null,
      'Only one of `above` and `below` may be specified.',
    );
    assert(
      above == null || (above._overlay == this && _entries.contains(above)),
      'The provided entry for `above` is not present in the Overlay.',
    );
    assert(
      below == null || (below._overlay == this && _entries.contains(below)),
      'The provided entry for `below` is not present in the Overlay.',
    );
    assert(!_entries.contains(entry), 'The specified entry is already present in the Overlay.');
    assert(entry._overlay == null, 'The specified entry is already present in another Overlay.');
323
    entry._overlay = this;
324
    setState(() {
325
      _entries.insert(_insertionIndex(below, above), entry);
326 327 328
    });
  }

329 330
  /// Insert all the entries in the given iterable.
  ///
331
  /// If `below` is non-null, the entries are inserted just below `below`.
332
  /// If `above` is non-null, the entries are inserted just above `above`.
333
  /// Otherwise, the entries are inserted on top.
334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356
  ///
  /// It is an error to specify both `above` and `below`.
  void insertAll(Iterable<OverlayEntry> entries, { OverlayEntry below, OverlayEntry above }) {
    assert(
      above == null || below == null,
      'Only one of `above` and `below` may be specified.',
    );
    assert(
      above == null || (above._overlay == this && _entries.contains(above)),
      'The provided entry for `above` is not present in the Overlay.',
    );
    assert(
      below == null || (below._overlay == this && _entries.contains(below)),
      'The provided entry for `below` is not present in the Overlay.',
    );
    assert(
      entries.every((OverlayEntry entry) => !_entries.contains(entry)),
      'One or more of the specified entries are already present in the Overlay.'
    );
    assert(
      entries.every((OverlayEntry entry) => entry._overlay == null),
      'One or more of the specified entries are already present in another Overlay.'
    );
Adam Barth's avatar
Adam Barth committed
357 358
    if (entries.isEmpty)
      return;
359
    for (final OverlayEntry entry in entries) {
360 361
      assert(entry._overlay == null);
      entry._overlay = this;
362 363
    }
    setState(() {
364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411
      _entries.insertAll(_insertionIndex(below, above), entries);
    });
  }

  /// Remove all the entries listed in the given iterable, then reinsert them
  /// into the overlay in the given order.
  ///
  /// Entries mention in `newEntries` but absent from the overlay are inserted
  /// as if with [insertAll].
  ///
  /// Entries not mentioned in `newEntries` but present in the overlay are
  /// positioned as a group in the resulting list relative to the entries that
  /// were moved, as specified by one of `below` or `above`, which, if
  /// specified, must be one of the entries in `newEntries`:
  ///
  /// If `below` is non-null, the group is positioned just below `below`.
  /// If `above` is non-null, the group is positioned just above `above`.
  /// Otherwise, the group is left on top, with all the rearranged entries
  /// below.
  ///
  /// It is an error to specify both `above` and `below`.
  void rearrange(Iterable<OverlayEntry> newEntries, { OverlayEntry below, OverlayEntry above }) {
    final List<OverlayEntry> newEntriesList = newEntries is List<OverlayEntry> ? newEntries : newEntries.toList(growable: false);
    assert(
      above == null || below == null,
      'Only one of `above` and `below` may be specified.',
    );
    assert(
      above == null || (above._overlay == this && _entries.contains(above) && newEntriesList.contains(above)),
      'The entry used for `above` must be in the Overlay and in the `newEntriesList`.'
    );
    assert(
      below == null || (below._overlay == this && _entries.contains(below) && newEntriesList.contains(below)),
      'The entry used for `below` must be in the Overlay and in the `newEntriesList`.'
    );
    assert(
      newEntriesList.every((OverlayEntry entry) => entry._overlay == null || entry._overlay == this),
      'One or more of the specified entries are already present in another Overlay.'
    );
    assert(
      newEntriesList.every((OverlayEntry entry) => _entries.indexOf(entry) == _entries.lastIndexOf(entry)),
      'One or more of the specified entries are specified multiple times.'
    );
    if (newEntriesList.isEmpty)
      return;
    if (listEquals(_entries, newEntriesList))
      return;
    final LinkedHashSet<OverlayEntry> old = LinkedHashSet<OverlayEntry>.from(_entries);
412
    for (final OverlayEntry entry in newEntriesList) {
413 414 415 416 417 418 419
      entry._overlay ??= this;
    }
    setState(() {
      _entries.clear();
      _entries.addAll(newEntriesList);
      old.removeAll(newEntriesList);
      _entries.insertAll(_insertionIndex(below, above), old);
420 421 422
    });
  }

423
  void _remove(OverlayEntry entry) {
424
    if (mounted) {
425 426 427
      setState(() {
        _entries.remove(entry);
      });
428
    }
429 430
  }

431 432
  /// (DEBUG ONLY) Check whether a given entry is visible (i.e., not behind an
  /// opaque entry).
433
  ///
434 435
  /// This is an O(N) algorithm, and should not be necessary except for debug
  /// asserts. To avoid people depending on it, this function is implemented
436
  /// only in debug mode, and always returns false in release mode.
437 438 439 440 441
  bool debugIsVisible(OverlayEntry entry) {
    bool result = false;
    assert(_entries.contains(entry));
    assert(() {
      for (int i = _entries.length - 1; i > 0; i -= 1) {
442
        final OverlayEntry candidate = _entries[i];
443 444 445 446
        if (candidate == entry) {
          result = true;
          break;
        }
Hixie's avatar
Hixie committed
447
        if (candidate.opaque)
448 449 450
          break;
      }
      return true;
451
    }());
452 453 454
    return result;
  }

455 456 457 458 459 460 461
  void _didChangeEntryOpacity() {
    setState(() {
      // We use the opacity of the entry in our build function, which means we
      // our state has changed.
    });
  }

462
  @override
463
  Widget build(BuildContext context) {
464 465 466
    // This list is filled backwards and then reversed below before
    // it is added to the tree.
    final List<Widget> children = <Widget>[];
467
    bool onstage = true;
468
    int onstageCount = 0;
469
    for (int i = _entries.length - 1; i >= 0; i -= 1) {
470
      final OverlayEntry entry = _entries[i];
471
      if (onstage) {
472 473 474 475 476
        onstageCount += 1;
        children.add(_OverlayEntryWidget(
          key: entry._key,
          entry: entry,
        ));
477 478 479
        if (entry.opaque)
          onstage = false;
      } else if (entry.maintainState) {
480 481 482 483 484
        children.add(_OverlayEntryWidget(
          key: entry._key,
          entry: entry,
          tickerEnabled: false,
        ));
485
      }
486
    }
487
    return _Theatre(
488 489
      skipCount: children.length - onstageCount,
      children: children.reversed.toList(growable: false),
490
    );
491
  }
492

493
  @override
494 495
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
496 497
    // TODO(jacobr): use IterableProperty instead as that would
    // provide a slightly more consistent string summary of the List.
498
    properties.add(DiagnosticsProperty<List<OverlayEntry>>('entries', _entries));
499
  }
500
}
501

502 503
/// Special version of a [Stack], that doesn't layout and render the first
/// [skipCount] children.
504
///
505 506
/// The first [skipCount] children are considered "offstage".
class _Theatre extends MultiChildRenderObjectWidget {
507
  _Theatre({
508 509 510 511 512 513 514 515
    Key key,
    this.skipCount = 0,
    List<Widget> children = const <Widget>[],
  }) : assert(skipCount != null),
       assert(skipCount >= 0),
       assert(children != null),
       assert(children.length >= skipCount),
       super(key: key, children: children);
516

517
  final int skipCount;
518 519

  @override
520
  _TheatreElement createElement() => _TheatreElement(this);
521 522

  @override
523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541
  _RenderTheatre createRenderObject(BuildContext context) {
    return _RenderTheatre(
      skipCount: skipCount,
      textDirection: Directionality.of(context),
    );
  }

  @override
  void updateRenderObject(BuildContext context, _RenderTheatre renderObject) {
    renderObject
      ..skipCount = skipCount
      ..textDirection = Directionality.of(context);
  }

  @override
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
    properties.add(IntProperty('skipCount', skipCount));
  }
542 543
}

544 545
class _TheatreElement extends MultiChildRenderObjectElement {
  _TheatreElement(_Theatre widget) : super(widget);
546 547

  @override
548
  _Theatre get widget => super.widget as _Theatre;
549 550

  @override
551
  _RenderTheatre get renderObject => super.renderObject as _RenderTheatre;
552

553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571
  @override
  void debugVisitOnstageChildren(ElementVisitor visitor) {
    assert(children.length >= widget.skipCount);
    children.skip(widget.skipCount).forEach(visitor);
  }
}

class _RenderTheatre extends RenderBox with ContainerRenderObjectMixin<RenderBox, StackParentData> {
  _RenderTheatre({
    List<RenderBox> children,
    @required TextDirection textDirection,
    int skipCount = 0,
  }) : assert(skipCount != null),
       assert(skipCount >= 0),
       assert(textDirection != null),
       _textDirection = textDirection,
       _skipCount = skipCount {
    addAll(children);
  }
572

573
  bool _hasVisualOverflow = false;
574 575

  @override
576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609
  void setupParentData(RenderBox child) {
    if (child.parentData is! StackParentData)
      child.parentData = StackParentData();
  }

  Alignment _resolvedAlignment;

  void _resolve() {
    if (_resolvedAlignment != null)
      return;
    _resolvedAlignment = AlignmentDirectional.topStart.resolve(textDirection);
  }

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

  TextDirection get textDirection => _textDirection;
  TextDirection _textDirection;
  set textDirection(TextDirection value) {
    if (_textDirection == value)
      return;
    _textDirection = value;
    _markNeedResolution();
  }

  int get skipCount => _skipCount;
  int _skipCount;
  set skipCount(int value) {
    assert(value != null);
    if (_skipCount != value) {
      _skipCount = value;
      markNeedsLayout();
610 611 612
    }
  }

613 614 615 616 617 618 619 620 621
  RenderBox get _firstOnstageChild {
    if (skipCount == super.childCount) {
      return null;
    }
    RenderBox child = super.firstChild;
    for (int toSkip = skipCount; toSkip > 0; toSkip--) {
      final StackParentData childParentData = child.parentData as StackParentData;
      child = childParentData.nextSibling;
      assert(child != null);
622
    }
623
    return child;
624 625
  }

626 627 628 629
  RenderBox get _lastOnstageChild => skipCount == super.childCount ? null : lastChild;

  int get _onstageChildCount => childCount - skipCount;

630
  @override
631 632
  double computeMinIntrinsicWidth(double height) {
    return RenderStack.getIntrinsicDimension(_firstOnstageChild, (RenderBox child) => child.getMinIntrinsicWidth(height));
633 634 635
  }

  @override
636 637
  double computeMaxIntrinsicWidth(double height) {
    return RenderStack.getIntrinsicDimension(_firstOnstageChild, (RenderBox child) => child.getMaxIntrinsicWidth(height));
638 639 640
  }

  @override
641 642
  double computeMinIntrinsicHeight(double width) {
    return RenderStack.getIntrinsicDimension(_firstOnstageChild, (RenderBox child) => child.getMinIntrinsicHeight(width));
643 644 645
  }

  @override
646 647
  double computeMaxIntrinsicHeight(double width) {
    return RenderStack.getIntrinsicDimension(_firstOnstageChild, (RenderBox child) => child.getMaxIntrinsicHeight(width));
648 649 650
  }

  @override
651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667
  double computeDistanceToActualBaseline(TextBaseline baseline) {
    assert(!debugNeedsLayout);
    double result;
    RenderBox child = _firstOnstageChild;
    while (child != null) {
      assert(!child.debugNeedsLayout);
      final StackParentData childParentData = child.parentData as StackParentData;
      double candidate = child.getDistanceToActualBaseline(baseline);
      if (candidate != null) {
        candidate += childParentData.offset.dy;
        if (result != null) {
          result = math.min(result, candidate);
        } else {
          result = candidate;
        }
      }
      child = childParentData.nextSibling;
668
    }
669
    return result;
670 671 672
  }

  @override
673 674 675 676 677 678
  bool get sizedByParent => true;

  @override
  void performResize() {
    size = constraints.biggest;
    assert(size.isFinite);
679 680
  }

681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709
  @override
  void performLayout() {
    _hasVisualOverflow = false;

    if (_onstageChildCount == 0) {
      return;
    }

    _resolve();
    assert(_resolvedAlignment != null);

    // Same BoxConstraints as used by RenderStack for StackFit.expand.
    final BoxConstraints nonPositionedConstraints = BoxConstraints.tight(constraints.biggest);

    RenderBox child = _firstOnstageChild;
    while (child != null) {
      final StackParentData childParentData = child.parentData as StackParentData;

      if (!childParentData.isPositioned) {
        child.layout(nonPositionedConstraints, parentUsesSize: true);
        childParentData.offset = _resolvedAlignment.alongOffset(size - child.size as Offset);
      } else {
        _hasVisualOverflow = RenderStack.layoutPositionedChild(child, childParentData, size, _resolvedAlignment) || _hasVisualOverflow;
      }

      assert(child.parentData == childParentData);
      child = childParentData.nextSibling;
    }
  }
710 711

  @override
712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729
  bool hitTestChildren(BoxHitTestResult result, { Offset position }) {
    RenderBox child = _lastOnstageChild;
    for (int i = 0; i < _onstageChildCount; i++) {
      assert(child != null);
      final StackParentData childParentData = child.parentData as StackParentData;
      final bool isHit = result.addWithPaintOffset(
        offset: childParentData.offset,
        position: position,
        hitTest: (BoxHitTestResult result, Offset transformed) {
          assert(transformed == position - childParentData.offset);
          return child.hitTest(result, position: transformed);
        },
      );
      if (isHit)
        return true;
      child = childParentData.previousSibling;
    }
    return false;
730 731
  }

732 733 734 735 736 737 738 739 740
  @protected
  void paintStack(PaintingContext context, Offset offset) {
    RenderBox child = _firstOnstageChild;
    while (child != null) {
      final StackParentData childParentData = child.parentData as StackParentData;
      context.paintChild(child, childParentData.offset + offset);
      child = childParentData.nextSibling;
    }
  }
741 742

  @override
743 744 745 746 747 748
  void paint(PaintingContext context, Offset offset) {
    if (_hasVisualOverflow) {
      context.pushClipRect(needsCompositing, offset, Offset.zero & size, paintStack);
    } else {
      paintStack(context, offset);
    }
749 750 751
  }

  @override
752 753 754
  void visitChildrenForSemantics(RenderObjectVisitor visitor) {
    RenderBox child = _firstOnstageChild;
    while (child != null) {
755
      visitor(child);
756 757 758
      final StackParentData childParentData = child.parentData as StackParentData;
      child = childParentData.nextSibling;
    }
759
  }
760

761
  @override
762
  Rect describeApproximatePaintClip(RenderObject child) => _hasVisualOverflow ? Offset.zero & size : null;
763

764 765 766 767 768 769
  @override
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
    properties.add(IntProperty('skipCount', skipCount));
    properties.add(EnumProperty<TextDirection>('textDirection', textDirection));
  }
770

771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793
  @override
  List<DiagnosticsNode> debugDescribeChildren() {
    final List<DiagnosticsNode> offstageChildren = <DiagnosticsNode>[];
    final List<DiagnosticsNode> onstageChildren = <DiagnosticsNode>[];

    int count = 1;
    bool onstage = false;
    RenderBox child = firstChild;
    final RenderBox firstOnstageChild = _firstOnstageChild;
    while (child != null) {
      if (child == firstOnstageChild) {
        onstage = true;
        count = 1;
      }

      if (onstage) {
        onstageChildren.add(
          child.toDiagnosticsNode(
            name: 'onstage $count',
          ),
        );
      } else {
        offstageChildren.add(
794 795 796 797 798
          child.toDiagnosticsNode(
            name: 'offstage $count',
            style: DiagnosticsTreeStyle.offstage,
          ),
        );
799
      }
800 801 802 803 804 805 806 807 808 809 810

      final StackParentData childParentData = child.parentData as StackParentData;
      child = childParentData.nextSibling;
      count += 1;
    }

    return <DiagnosticsNode>[
      ...onstageChildren,
      if (offstageChildren.isNotEmpty)
        ...offstageChildren
      else
811
        DiagnosticsNode.message(
812 813 814
          'no offstage children',
          style: DiagnosticsTreeStyle.offstage,
        ),
815
    ];
816
  }
817
}