overlay.dart 19.9 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 47 48
/// 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
/// call [setState], the user's battery will be drained unnecessarily.
///
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 65
    bool opaque: false,
    bool maintainState: false,
  }) : _opaque = opaque, _maintainState = maintainState {
66
    assert(builder != null);
67 68
    assert(opaque != null);
    assert(maintainState != null);
69
  }
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 102 103 104 105 106 107 108
  /// 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
  /// call [setState], the user's battery will be drained unnecessarily.
  ///
  /// 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 = new GlobalKey<_OverlayEntryState>();
120

121
  /// Remove this entry from the overlay.
122 123 124 125 126 127 128 129 130 131
  ///
  /// This should only be called once.
  ///
  /// If this method is called while the [SchedulerBinding.schedulerPhase] is
  /// [SchedulerBinding.persistentCallbacks], i.e. during the build, layout, or
  /// paint phases (see [WidgetsBinding.beginFrame]), then the removal is
  /// 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() => '$runtimeType#$hashCode(opaque: $opaque; maintainState: $maintainState)';
154 155
}

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

161
  final OverlayEntry entry;
162 163

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

167
class _OverlayEntryState extends State<_OverlayEntry> {
168
  @override
169 170 171
  Widget build(BuildContext context) {
    return config.entry.builder(context);
  }
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 201 202 203
  /// Creates an overlay.
  ///
  /// The initial entries will be inserted into the overlay when its associated
  /// [OverlayState] is initialized.
  ///
  /// Rather than creating an overlay, consider using the overlay that has
  /// already been created by the [WidgetsApp] or the [MaterialApp] for this
  /// application.
204 205
  Overlay({
    Key key,
Adam Barth's avatar
Adam Barth committed
206 207 208 209
    this.initialEntries: const <OverlayEntry>[]
  }) : super(key: key) {
    assert(initialEntries != null);
  }
210

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

226
  /// The state from the closest instance of this class that encloses the given context.
227 228 229 230 231 232
  ///
  /// 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.
233 234 235 236 237 238
  ///
  /// Typical usage is as follows:
  ///
  /// ```dart
  /// OverlayState overlay = Overlay.of(context);
  /// ```
239
  static OverlayState of(BuildContext context, { Widget debugRequiredFor }) {
240
    final OverlayState result = context.ancestorStateOfType(const TypeMatcher<OverlayState>());
241 242
    assert(() {
      if (debugRequiredFor != null && result == null) {
243
        final String additional = context.widget != debugRequiredFor
244 245
          ? '\nThe context from which that widget was searching for an overlay was:\n  $context'
          : '';
246
        throw new FlutterError(
247 248 249 250 251 252 253 254 255 256 257 258
          '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;
    });
    return result;
  }
Hixie's avatar
Hixie committed
259

260
  @override
261 262 263
  OverlayState createState() => new OverlayState();
}

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

271
  @override
272 273
  void initState() {
    super.initState();
274
    insertAll(config.initialEntries);
275 276
  }

277 278 279 280
  /// 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.
281
  void insert(OverlayEntry entry, { OverlayEntry above }) {
282 283 284
    assert(entry._overlay == null);
    assert(above == null || (above._overlay == this && _entries.contains(above)));
    entry._overlay = this;
285
    setState(() {
286
      final int index = above == null ? _entries.length : _entries.indexOf(above) + 1;
287 288 289 290
      _entries.insert(index, entry);
    });
  }

291 292 293 294
  /// 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.
295
  void insertAll(Iterable<OverlayEntry> entries, { OverlayEntry above }) {
296
    assert(above == null || (above._overlay == this && _entries.contains(above)));
Adam Barth's avatar
Adam Barth committed
297 298
    if (entries.isEmpty)
      return;
299
    for (OverlayEntry entry in entries) {
300 301
      assert(entry._overlay == null);
      entry._overlay = this;
302 303
    }
    setState(() {
304
      final int index = above == null ? _entries.length : _entries.indexOf(above) + 1;
305 306 307 308
      _entries.insertAll(index, entries);
    });
  }

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

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

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

347
  @override
348
  Widget build(BuildContext context) {
349 350 351 352 353 354 355
    // 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) {
356
      final OverlayEntry entry = _entries[i];
357 358 359 360 361
      if (onstage) {
        onstageChildren.add(new _OverlayEntry(entry));
        if (entry.opaque)
          onstage = false;
      } else if (entry.maintainState) {
362
        offstageChildren.add(new TickerMode(enabled: false, child: new _OverlayEntry(entry)));
363
      }
364
    }
365 366 367 368
    return new _Theatre(
      onstage: new Stack(children: onstageChildren.reversed.toList(growable: false)),
      offstage: offstageChildren,
    );
369
  }
370

371
  @override
372 373 374 375
  void debugFillDescription(List<String> description) {
    super.debugFillDescription(description);
    description.add('entries: $_entries');
  }
376
}
377 378 379 380 381 382 383 384 385 386 387 388

/// 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,
389
    @required this.offstage,
390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420
  }) {
    assert(offstage != null);
    assert(!offstage.any((Widget child) => child == null));
  }

  final Stack onstage;

  final List<Widget> offstage;

  @override
  _TheatreElement createElement() => new _TheatreElement(this);

  @override
  _RenderTheatre createRenderObject(BuildContext context) => new _RenderTheatre();
}

class _TheatreElement extends RenderObjectElement {
  _TheatreElement(_Theatre widget) : super(widget) {
    assert(!debugChildrenHaveDuplicateKeys(widget, widget.offstage));
  }

  @override
  _Theatre get widget => super.widget;

  @override
  _RenderTheatre get renderObject => super.renderObject;

  Element _onstage;
  static final Object _onstageSlot = new Object();

  List<Element> _offstage;
421
  final Set<Element> _forgottenOffstageChildren = new HashSet<Element>();
422 423 424 425 426 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

  @override
  void insertChildRenderObject(RenderBox child, dynamic slot) {
    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) {
465
      if (!_forgottenOffstageChildren.contains(child))
466 467 468 469 470 471 472 473 474 475 476
        visitor(child);
    }
  }

  @override
  void visitChildrenForSemantics(ElementVisitor visitor) {
    if (_onstage != null)
      visitor(_onstage);
  }

  @override
477
  bool forgetChild(Element child) {
478 479 480
    if (child == _onstage) {
      _onstage = null;
    } else {
481
      assert(_offstage.contains(child));
482 483
      assert(!_forgottenOffstageChildren.contains(child));
      _forgottenOffstageChildren.add(child);
484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505
    }
    return true;
  }

  @override
  void mount(Element parent, dynamic newSlot) {
    super.mount(parent, newSlot);
    _onstage = updateChild(_onstage, widget.onstage, _onstageSlot);
    _offstage = new List<Element>(widget.offstage.length);
    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);
506 507
    _offstage = updateChildren(_offstage, widget.offstage, forgottenChildren: _forgottenOffstageChildren);
    _forgottenOffstageChildren.clear();
508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 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 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587
  }
}

// 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
  with RenderObjectWithChildMixin<RenderStack>, RenderProxyBoxMixin,
       ContainerRenderObjectMixin<RenderBox, StackParentData> {

  @override
  void setupParentData(RenderObject child) {
    if (child.parentData is! StackParentData)
      child.parentData = new StackParentData();
  }

  // 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
  String debugDescribeChildren(String prefix) {
    String result = '';
    if (child != null)
      result += '$prefix \u2502\n${child.toStringDeep('$prefix \u251C\u2500onstage: ', '$prefix \u254E')}';
    if (firstChild != null) {
      RenderBox child = firstChild;
      int count = 1;
      while (child != lastChild) {
        result += '${child.toStringDeep("$prefix \u254E\u254Coffstage $count: ", "$prefix \u254E")}';
        count += 1;
        final StackParentData childParentData = child.parentData;
        child = childParentData.nextSibling;
      }
      if (child != null) {
        assert(child == lastChild);
        result += '${child.toStringDeep("$prefix \u2514\u254Coffstage $count: ", "$prefix  ")}';
      }
    } else {
      result += '$prefix \u2514\u254Cno offstage children';
    }
    return result;
  }

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