overlay.dart 20.2 KB
Newer Older
1 2 3 4
// Copyright 2015 The Chromium Authors. All rights reserved.
// 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 7
import 'dart:collection';

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

12
import 'basic.dart';
13
import 'debug.dart';
14
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
    assert(_overlay != null);
90
    _overlay._didChangeEntryOpacity();
91 92
  }

93 94 95 96 97 98 99 100 101
  /// 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
102
  /// call [State.setState], the user's battery will be drained unnecessarily.
103 104 105 106 107 108
  ///
  /// 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;
109
  set maintainState(bool value) {
110 111 112 113 114 115 116 117
    assert(_maintainState != null);
    if (_maintainState == value)
      return;
    _maintainState = value;
    assert(_overlay != null);
    _overlay._didChangeEntryOpacity();
  }

118
  OverlayState _overlay;
119
  final GlobalKey<_OverlayEntryState> _key = GlobalKey<_OverlayEntryState>();
120

121
  /// Remove this entry from the overlay.
122 123 124 125
  ///
  /// This should only be called once.
  ///
  /// If this method is called while the [SchedulerBinding.schedulerPhase] is
126 127
  /// [SchedulerPhase.persistentCallbacks], i.e. during the build, layout, or
  /// paint phases (see [WidgetsBinding.drawFrame]), then the removal is
128 129 130 131
  /// 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).
132
  void remove() {
133
    assert(_overlay != null);
134
    final OverlayState overlay = _overlay;
135
    _overlay = null;
136 137 138 139 140 141 142
    if (SchedulerBinding.instance.schedulerPhase == SchedulerPhase.persistentCallbacks) {
      SchedulerBinding.instance.addPostFrameCallback((Duration duration) {
        overlay._remove(this);
      });
    } else {
      overlay._remove(this);
    }
143
  }
144

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

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

156
class _OverlayEntry extends StatefulWidget {
157 158 159
  _OverlayEntry(this.entry)
    : assert(entry != null),
      super(key: entry._key);
160

161
  final OverlayEntry entry;
162 163

  @override
164
  _OverlayEntryState createState() => _OverlayEntryState();
165
}
166

167
class _OverlayEntryState extends State<_OverlayEntry> {
168
  @override
169
  Widget build(BuildContext context) {
170
    return widget.entry.builder(context);
171
  }
172 173 174 175

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

178
/// A [Stack] of entries that can be managed independently.
179 180 181 182 183 184 185 186 187 188 189 190
///
/// 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:
///
191 192 193 194
///  * [OverlayEntry].
///  * [OverlayState].
///  * [WidgetsApp].
///  * [MaterialApp].
195
class Overlay extends StatefulWidget {
196 197 198 199 200
  /// Creates an overlay.
  ///
  /// The initial entries will be inserted into the overlay when its associated
  /// [OverlayState] is initialized.
  ///
201 202
  /// Rather than creating an overlay, consider using the overlay that is
  /// created by the [WidgetsApp] or the [MaterialApp] for the application.
203
  const Overlay({
204
    Key key,
205
    this.initialEntries = const <OverlayEntry>[]
206 207
  }) : assert(initialEntries != null),
       super(key: key);
208

209
  /// The entries to include in the overlay initially.
210 211 212 213 214 215 216 217
  ///
  /// 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
218 219
  /// [GlobalKey.currentState]), and then use [OverlayState.insert] or
  /// [OverlayState.insertAll].
220 221
  ///
  /// To remove an entry from an [Overlay], use [OverlayEntry.remove].
222 223
  final List<OverlayEntry> initialEntries;

224
  /// The state from the closest instance of this class that encloses the given context.
225 226 227 228 229 230
  ///
  /// In checked mode, if the [debugRequiredFor] argument is provided then this
  /// 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
  /// one given by the [debugRequiredFor] argument) needs an [Overlay] to be
  /// present to function.
231 232 233 234 235 236
  ///
  /// Typical usage is as follows:
  ///
  /// ```dart
  /// OverlayState overlay = Overlay.of(context);
  /// ```
237
  static OverlayState of(BuildContext context, { Widget debugRequiredFor }) {
238
    final OverlayState result = context.ancestorStateOfType(const TypeMatcher<OverlayState>());
239 240
    assert(() {
      if (debugRequiredFor != null && result == null) {
241
        final String additional = context.widget != debugRequiredFor
242 243
          ? '\nThe context from which that widget was searching for an overlay was:\n  $context'
          : '';
244
        throw FlutterError(
245 246 247 248 249 250 251 252 253
          'No Overlay widget found.\n'
          '${debugRequiredFor.runtimeType} widgets require an Overlay widget ancestor for correct operation.\n'
          'The most common way to add an Overlay to an application is to include a MaterialApp or Navigator widget in the runApp() call.\n'
          'The specific widget that failed to find an overlay was:\n'
          '  $debugRequiredFor'
          '$additional'
        );
      }
      return true;
254
    }());
255 256
    return result;
  }
Hixie's avatar
Hixie committed
257

258
  @override
259
  OverlayState createState() => OverlayState();
260 261
}

262
/// The current state of an [Overlay].
263 264 265
///
/// Used to insert [OverlayEntry]s into the overlay using the [insert] and
/// [insertAll] functions.
266
class OverlayState extends State<Overlay> with TickerProviderStateMixin {
267
  final List<OverlayEntry> _entries = <OverlayEntry>[];
268

269
  @override
270 271
  void initState() {
    super.initState();
272
    insertAll(widget.initialEntries);
273 274
  }

275 276 277 278
  /// Insert the given entry into the overlay.
  ///
  /// If [above] is non-null, the entry is inserted just above [above].
  /// Otherwise, the entry is inserted on top.
279
  void insert(OverlayEntry entry, { OverlayEntry above }) {
280 281 282
    assert(entry._overlay == null);
    assert(above == null || (above._overlay == this && _entries.contains(above)));
    entry._overlay = this;
283
    setState(() {
284
      final int index = above == null ? _entries.length : _entries.indexOf(above) + 1;
285 286 287 288
      _entries.insert(index, entry);
    });
  }

289 290 291 292
  /// Insert all the entries in the given iterable.
  ///
  /// If [above] is non-null, the entries are inserted just above [above].
  /// Otherwise, the entries are inserted on top.
293
  void insertAll(Iterable<OverlayEntry> entries, { OverlayEntry above }) {
294
    assert(above == null || (above._overlay == this && _entries.contains(above)));
Adam Barth's avatar
Adam Barth committed
295 296
    if (entries.isEmpty)
      return;
297
    for (OverlayEntry entry in entries) {
298 299
      assert(entry._overlay == null);
      entry._overlay = this;
300 301
    }
    setState(() {
302
      final int index = above == null ? _entries.length : _entries.indexOf(above) + 1;
303 304 305 306
      _entries.insertAll(index, entries);
    });
  }

307
  void _remove(OverlayEntry entry) {
308 309
    if (mounted) {
      _entries.remove(entry);
310
      setState(() { /* entry was removed */ });
311
    }
312 313
  }

314 315
  /// (DEBUG ONLY) Check whether a given entry is visible (i.e., not behind an
  /// opaque entry).
316
  ///
317 318 319
  /// 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
  /// only in checked mode.
320 321 322 323 324
  bool debugIsVisible(OverlayEntry entry) {
    bool result = false;
    assert(_entries.contains(entry));
    assert(() {
      for (int i = _entries.length - 1; i > 0; i -= 1) {
325
        final OverlayEntry candidate = _entries[i];
326 327 328 329
        if (candidate == entry) {
          result = true;
          break;
        }
Hixie's avatar
Hixie committed
330
        if (candidate.opaque)
331 332 333
          break;
      }
      return true;
334
    }());
335 336 337
    return result;
  }

338 339 340 341 342 343 344
  void _didChangeEntryOpacity() {
    setState(() {
      // We use the opacity of the entry in our build function, which means we
      // our state has changed.
    });
  }

345
  @override
346
  Widget build(BuildContext context) {
347 348 349 350 351 352 353
    // These lists are filled backwards. For the offstage children that
    // does not matter since they aren't rendered, but for the onstage
    // children we reverse the list below before adding it to the tree.
    final List<Widget> onstageChildren = <Widget>[];
    final List<Widget> offstageChildren = <Widget>[];
    bool onstage = true;
    for (int i = _entries.length - 1; i >= 0; i -= 1) {
354
      final OverlayEntry entry = _entries[i];
355
      if (onstage) {
356
        onstageChildren.add(_OverlayEntry(entry));
357 358 359
        if (entry.opaque)
          onstage = false;
      } else if (entry.maintainState) {
360
        offstageChildren.add(TickerMode(enabled: false, child: _OverlayEntry(entry)));
361
      }
362
    }
363 364
    return _Theatre(
      onstage: Stack(
365
        fit: StackFit.expand,
366 367
        children: onstageChildren.reversed.toList(growable: false),
      ),
368 369
      offstage: offstageChildren,
    );
370
  }
371

372
  @override
373 374
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
375 376
    // TODO(jacobr): use IterableProperty instead as that would
    // provide a slightly more consistent string summary of the List.
377
    properties.add(DiagnosticsProperty<List<OverlayEntry>>('entries', _entries));
378
  }
379
}
380 381 382 383 384 385 386 387 388 389 390 391

/// A widget that has one [onstage] child which is visible, and one or more
/// [offstage] widgets which are kept alive, and are built, but are not laid out
/// or painted.
///
/// The onstage widget must be a Stack.
///
/// For convenience, it is legal to use [Positioned] widgets around the offstage
/// widgets.
class _Theatre extends RenderObjectWidget {
  _Theatre({
    this.onstage,
392
    @required this.offstage,
393 394
  }) : assert(offstage != null),
       assert(!offstage.any((Widget child) => child == null));
395 396 397 398 399 400

  final Stack onstage;

  final List<Widget> offstage;

  @override
401
  _TheatreElement createElement() => _TheatreElement(this);
402 403

  @override
404
  _RenderTheatre createRenderObject(BuildContext context) => _RenderTheatre();
405 406 407
}

class _TheatreElement extends RenderObjectElement {
408 409 410
  _TheatreElement(_Theatre widget)
    : assert(!debugChildrenHaveDuplicateKeys(widget, widget.offstage)),
      super(widget);
411 412 413 414 415 416 417 418

  @override
  _Theatre get widget => super.widget;

  @override
  _RenderTheatre get renderObject => super.renderObject;

  Element _onstage;
419
  static final Object _onstageSlot = Object();
420 421

  List<Element> _offstage;
422
  final Set<Element> _forgottenOffstageChildren = HashSet<Element>();
423 424 425

  @override
  void insertChildRenderObject(RenderBox child, dynamic slot) {
426
    assert(renderObject.debugValidateChild(child));
427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466
    if (slot == _onstageSlot) {
      assert(child is RenderStack);
      renderObject.child = child;
    } else {
      assert(slot == null || slot is Element);
      renderObject.insert(child, after: slot?.renderObject);
    }
  }

  @override
  void moveChildRenderObject(RenderBox child, dynamic slot) {
    if (slot == _onstageSlot) {
      renderObject.remove(child);
      assert(child is RenderStack);
      renderObject.child = child;
    } else {
      assert(slot == null || slot is Element);
      if (renderObject.child == child) {
        renderObject.child = null;
        renderObject.insert(child, after: slot?.renderObject);
      } else {
        renderObject.move(child, after: slot?.renderObject);
      }
    }
  }

  @override
  void removeChildRenderObject(RenderBox child) {
    if (renderObject.child == child) {
      renderObject.child = null;
    } else {
      renderObject.remove(child);
    }
  }

  @override
  void visitChildren(ElementVisitor visitor) {
    if (_onstage != null)
      visitor(_onstage);
    for (Element child in _offstage) {
467
      if (!_forgottenOffstageChildren.contains(child))
468 469 470 471 472
        visitor(child);
    }
  }

  @override
473
  void debugVisitOnstageChildren(ElementVisitor visitor) {
474 475 476 477 478
    if (_onstage != null)
      visitor(_onstage);
  }

  @override
479
  bool forgetChild(Element child) {
480 481 482
    if (child == _onstage) {
      _onstage = null;
    } else {
483
      assert(_offstage.contains(child));
484 485
      assert(!_forgottenOffstageChildren.contains(child));
      _forgottenOffstageChildren.add(child);
486 487 488 489 490 491 492 493
    }
    return true;
  }

  @override
  void mount(Element parent, dynamic newSlot) {
    super.mount(parent, newSlot);
    _onstage = updateChild(_onstage, widget.onstage, _onstageSlot);
494
    _offstage = List<Element>(widget.offstage.length);
495 496 497 498 499 500 501 502 503 504 505 506 507
    Element previousChild;
    for (int i = 0; i < _offstage.length; i += 1) {
      final Element newChild = inflateWidget(widget.offstage[i], previousChild);
      _offstage[i] = newChild;
      previousChild = newChild;
    }
  }

  @override
  void update(_Theatre newWidget) {
    super.update(newWidget);
    assert(widget == newWidget);
    _onstage = updateChild(_onstage, widget.onstage, _onstageSlot);
508 509
    _offstage = updateChildren(_offstage, widget.offstage, forgottenChildren: _forgottenOffstageChildren);
    _forgottenOffstageChildren.clear();
510 511 512 513 514 515 516 517 518 519 520 521
  }
}

// A render object which lays out and paints one subtree while keeping a list
// of other subtrees alive but not laid out or painted (the "zombie" children).
//
// The subtree that is laid out and painted must be a [RenderStack].
//
// This class uses [StackParentData] objects for its parent data so that the
// children of its primary subtree's stack can be moved to this object's list
// of zombie children without changing their parent data objects.
class _RenderTheatre extends RenderBox
522
  with RenderObjectWithChildMixin<RenderStack>, RenderProxyBoxMixin<RenderStack>,
523 524 525 526 527
       ContainerRenderObjectMixin<RenderBox, StackParentData> {

  @override
  void setupParentData(RenderObject child) {
    if (child.parentData is! StackParentData)
528
      child.parentData = StackParentData();
529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561
  }

  // Because both RenderObjectWithChildMixin and ContainerRenderObjectMixin
  // define redepthChildren, visitChildren and debugDescribeChildren and don't
  // call super, we have to define them again here to make sure the work of both
  // is done.
  //
  // We chose to put ContainerRenderObjectMixin last in the inheritance chain so
  // that we can call super to hit its more complex definitions of
  // redepthChildren and visitChildren, and then duplicate the more trivial
  // definition from RenderObjectWithChildMixin inline in our version here.
  //
  // This code duplication is suboptimal.
  // TODO(ianh): Replace this with a better solution once https://github.com/dart-lang/sdk/issues/27100 is fixed
  //
  // For debugDescribeChildren we just roll our own because otherwise the line
  // drawings won't really work as well.

  @override
  void redepthChildren() {
    if (child != null)
      redepthChild(child);
    super.redepthChildren();
  }

  @override
  void visitChildren(RenderObjectVisitor visitor) {
    if (child != null)
      visitor(child);
    super.visitChildren(visitor);
  }

  @override
562 563 564
  List<DiagnosticsNode> debugDescribeChildren() {
    final List<DiagnosticsNode> children = <DiagnosticsNode>[];

565
    if (child != null)
566 567
      children.add(child.toDiagnosticsNode(name: 'onstage'));

568
    if (firstChild != null) {
569
      RenderBox child = firstChild;
570

571
      int count = 1;
572 573 574 575 576 577 578 579 580
      while (true) {
        children.add(
          child.toDiagnosticsNode(
            name: 'offstage $count',
            style: DiagnosticsTreeStyle.offstage,
          ),
        );
        if (child == lastChild)
          break;
581 582
        final StackParentData childParentData = child.parentData;
        child = childParentData.nextSibling;
583
        count += 1;
584 585
      }
    } else {
586
      children.add(
587
        DiagnosticsNode.message(
588 589 590 591
          'no offstage children',
          style: DiagnosticsTreeStyle.offstage,
        ),
      );
592
    }
593 594
    return children;
   }
595 596 597 598 599 600

  @override
  void visitChildrenForSemantics(RenderObjectVisitor visitor) {
    if (child != null)
      visitor(child);
  }
601
}