-
Notifications
You must be signed in to change notification settings - Fork 30.9k
Expand file tree
/
Copy pathoverlay.dart
More file actions
2996 lines (2726 loc) · 107 KB
/
Copy pathoverlay.dart
File metadata and controls
2996 lines (2726 loc) · 107 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
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
304
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
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
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
412
413
414
415
416
417
418
419
420
421
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
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
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
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
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
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/// @docImport 'package:flutter/cupertino.dart';
/// @docImport 'package:flutter/material.dart';
///
/// @docImport 'app.dart';
/// @docImport 'drag_target.dart';
/// @docImport 'implicit_animations.dart';
/// @docImport 'media_query.dart';
/// @docImport 'navigator.dart';
/// @docImport 'routes.dart';
/// @docImport 'scroll_view.dart';
/// @docImport 'sliver.dart';
/// @docImport 'text.dart';
library;
import 'dart:collection';
import 'package:flutter/foundation.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/scheduler.dart';
import 'basic.dart';
import 'framework.dart';
import 'layout_builder.dart';
import 'lookup_boundary.dart';
import 'media_query.dart';
import 'ticker_provider.dart';
/// The signature of the widget builder callback used in
/// [OverlayPortal.overlayChildLayoutBuilder].
typedef OverlayChildLayoutBuilder =
Widget Function(BuildContext context, OverlayChildLayoutInfo info);
/// The additional layout information available to the
/// [OverlayPortal.overlayChildLayoutBuilder] callback.
extension type OverlayChildLayoutInfo._(
(Size childSize, Matrix4 childPaintTransform, Size overlaySize) _info
) {
/// The size of [OverlayPortal.child] in its own coordinates.
Size get childSize => _info.$1;
/// The paint transform of [OverlayPortal.child], in the target [Overlay]'s
/// coordinates.
Matrix4 get childPaintTransform => _info.$2;
/// The size of the target [Overlay] in its own coordinates.
Size get overlaySize => _info.$3;
}
// Examples can assume:
// late BuildContext context;
// * OverlayEntry Implementation
/// 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. In 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.
///
/// 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 [State.setState], the user's battery will be drained unnecessarily.
///
/// [OverlayEntry] is a [Listenable] that notifies when the widget built by
/// [builder] is mounted or unmounted, whose exact state can be queried by
/// [mounted]. After the owner of the [OverlayEntry] calls [remove] and then
/// [dispose], the widget may not be immediately removed from the widget tree.
/// As a result listeners of the [OverlayEntry] can get notified for one last
/// time after the [dispose] call, when the widget is eventually unmounted.
///
/// {@macro flutter.widgets.overlayPortalVsOverlayEntry}
///
/// See also:
///
/// * [OverlayPortal], an alternative API for inserting widgets into an
/// [Overlay] using a builder callback.
/// * [Overlay], a stack of entries that can be managed independently.
/// * [OverlayState], the current state of an Overlay.
/// * [WidgetsApp], a convenience widget that wraps a number of widgets that
/// are commonly required for an application.
/// * [MaterialApp], a convenience widget that wraps a number of widgets that
/// are commonly required for Material Design applications.
class OverlayEntry implements Listenable {
/// 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.
OverlayEntry({
required this.builder,
bool opaque = false,
bool maintainState = false,
this.canSizeOverlay = false,
}) : _opaque = opaque,
_maintainState = maintainState {
assert(debugMaybeDispatchCreated('widgets', 'OverlayEntry', this));
}
/// This entry will include the widget built by this builder in the overlay at
/// the entry's position.
///
/// To cause this builder to be called again, call [markNeedsBuild] on this
/// overlay entry.
final WidgetBuilder builder;
/// Whether this entry occludes the entire overlay.
///
/// If an entry claims to be opaque, then, for efficiency, the overlay will
/// skip building entries below that entry unless they have [maintainState]
/// set.
bool get opaque => _opaque;
bool _opaque;
set opaque(bool value) {
assert(!_disposedByOwner);
if (_opaque == value) {
return;
}
_opaque = value;
_overlay?._didChangeEntryOpacity();
}
/// 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 [State.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;
set maintainState(bool value) {
assert(!_disposedByOwner);
if (_maintainState == value) {
return;
}
_maintainState = value;
assert(_overlay != null);
_overlay!._didChangeEntryOpacity();
}
/// Whether the content of this [OverlayEntry] can be used to size the
/// [Overlay].
///
/// In most situations the overlay sizes itself based on its incoming
/// constraints to be as large as possible. However, if that would result in
/// an infinite size, it has to rely on one of its children to size itself. In
/// this situation, the overlay will consult the topmost non-[Positioned]
/// overlay entry that has this property set to true, lay it out with the
/// incoming [BoxConstraints] of the overlay, and force all other
/// non-[Positioned] overlay entries to have the same size. The [Positioned]
/// entries are laid out as usual based on the calculated size of the overlay.
///
/// Overlay entries that set this to true must be able to handle unconstrained
/// [BoxConstraints].
///
/// Setting this to true has no effect if the overlay entry uses a [Positioned]
/// widget to position itself in the overlay.
final bool canSizeOverlay;
/// Whether the [OverlayEntry] is currently mounted in the widget tree.
///
/// The [OverlayEntry] notifies its listeners when this value changes.
bool get mounted => _overlayEntryStateNotifier?.value != null;
/// The currently mounted `_OverlayEntryWidgetState` built using this [OverlayEntry].
ValueNotifier<_OverlayEntryWidgetState?>? _overlayEntryStateNotifier =
ValueNotifier<_OverlayEntryWidgetState?>(null);
@override
void addListener(VoidCallback listener) {
assert(!_disposedByOwner);
_overlayEntryStateNotifier?.addListener(listener);
}
@override
void removeListener(VoidCallback listener) {
_overlayEntryStateNotifier?.removeListener(listener);
}
OverlayState? _overlay;
final GlobalKey<_OverlayEntryWidgetState> _key = GlobalKey<_OverlayEntryWidgetState>();
/// Remove this entry from the overlay.
///
/// This should only be called once.
///
/// This method removes this overlay entry from the overlay immediately. The
/// UI will be updated in the same frame if this method is called before the
/// overlay rebuild in this frame; otherwise, the UI will be updated in the
/// next frame. This means that it is safe to call during builds, but also
/// that if you do call this after the overlay rebuild, the UI will not update
/// until the next frame (i.e. many milliseconds later).
void remove() {
assert(_overlay != null, 'An OverlayEntry should be removed only once.');
assert(!_disposedByOwner);
final OverlayState overlay = _overlay!;
_overlay = null;
if (!overlay.mounted) {
return;
}
overlay._entries.remove(this);
if (SchedulerBinding.instance.schedulerPhase == SchedulerPhase.persistentCallbacks) {
SchedulerBinding.instance.addPostFrameCallback((Duration duration) {
overlay._markDirty();
}, debugLabel: 'OverlayEntry.markDirty');
} else {
overlay._markDirty();
}
}
/// Cause this entry to rebuild during the next pipeline flush.
///
/// You need to call this function if the output of [builder] has changed.
void markNeedsBuild() {
assert(!_disposedByOwner);
_key.currentState?._markNeedsBuild();
}
void _didUnmount() {
assert(!mounted);
if (_disposedByOwner) {
_overlayEntryStateNotifier?.dispose();
_overlayEntryStateNotifier = null;
}
}
bool _disposedByOwner = false;
/// Discards any resources used by this [OverlayEntry].
///
/// The [remove] method must be called before this method if the
/// [OverlayEntry] is inserted into an [Overlay].
///
/// After this is called, the object is not in a usable state and should be
/// discarded (calls to [addListener] will throw after the object is disposed).
/// However, the listeners registered may not be immediately released until
/// the widget built using this [OverlayEntry] is unmounted from the widget
/// tree.
///
/// This method should only be called by the object's owner.
void dispose() {
assert(!_disposedByOwner);
assert(
_overlay == null,
'An OverlayEntry must first be removed from the Overlay before dispose is called.',
);
assert(debugMaybeDispatchDisposed(this));
_disposedByOwner = true;
if (!mounted) {
// If we're still mounted when disposed, then this will be disposed in
// _didUnmount, to allow notifications to occur until the entry is
// unmounted.
_overlayEntryStateNotifier?.dispose();
_overlayEntryStateNotifier = null;
}
}
@override
String toString() =>
'${describeIdentity(this)}(opaque: $opaque; maintainState: $maintainState)${_disposedByOwner ? "(DISPOSED)" : ""}';
}
class _OverlayEntryWidget extends StatefulWidget {
const _OverlayEntryWidget({
required Key super.key,
required this.entry,
required this.overlayState,
this.tickerEnabled = true,
});
final OverlayEntry entry;
final OverlayState overlayState;
final bool tickerEnabled;
@override
_OverlayEntryWidgetState createState() => _OverlayEntryWidgetState();
}
class _OverlayEntryWidgetState extends State<_OverlayEntryWidget> {
late _RenderTheater _theater;
// Manages the stack of theater children whose paint order are sorted by their
// _zOrderIndex. The children added by OverlayPortal are added to this linked
// list, and they will be shown _above_ the OverlayEntry tied to this widget.
// The children with larger zOrderIndex values (i.e. those called `show`
// recently) will be painted last.
//
// This linked list is lazily created in `_add`, and the entries are added/removed
// via `_add`/`_remove`, called by OverlayPortals lower in the tree. `_add` or
// `_remove` does not cause this widget to rebuild, the linked list will be
// read by _RenderTheater as part of its render child model. This would ideally
// be in a RenderObject but there may not be RenderObjects between
// _RenderTheater and the render subtree OverlayEntry builds.
LinkedList<_OverlayEntryLocation>? _sortedTheaterSiblings;
// Worst-case O(N), N being the number of children added to the top spot in
// the same frame. This can be a bit expensive when there's a lot of global
// key reparenting in the same frame but N is usually a small number.
void _add(_OverlayEntryLocation child) {
assert(mounted);
final LinkedList<_OverlayEntryLocation> children = _sortedTheaterSiblings ??=
LinkedList<_OverlayEntryLocation>();
assert(!children.contains(child));
_OverlayEntryLocation? insertPosition = children.isEmpty ? null : children.last;
while (insertPosition != null && insertPosition._zOrderIndex > child._zOrderIndex) {
insertPosition = insertPosition.previous;
}
if (insertPosition == null) {
children.addFirst(child);
} else {
insertPosition.insertAfter(child);
}
assert(children.contains(child));
}
void _remove(_OverlayEntryLocation child) {
assert(_sortedTheaterSiblings != null);
final bool wasInCollection = _sortedTheaterSiblings?.remove(child) ?? false;
assert(wasInCollection);
}
// Returns an Iterable that traverse the children in the child model in paint
// order (from farthest to the user to the closest to the user).
//
// The iterator should be safe to use even when the child model is being
// mutated. The reason for that is it's allowed to add/remove/move deferred
// children to a _RenderTheater during performLayout, but the affected
// children don't have to be laid out in the same performLayout call.
late final Iterable<_RenderDeferredLayoutBox> _paintOrderIterable = _createChildIterable(
reversed: false,
);
// An Iterable that traverse the children in the child model in
// hit-test order (from closest to the user to the farthest to the user).
late final Iterable<_RenderDeferredLayoutBox> _hitTestOrderIterable = _createChildIterable(
reversed: true,
);
// The following uses sync* because hit-testing is lazy, and LinkedList as a
// Iterable doesn't support concurrent modification.
Iterable<_RenderDeferredLayoutBox> _createChildIterable({required bool reversed}) sync* {
final LinkedList<_OverlayEntryLocation>? children = _sortedTheaterSiblings;
if (children == null || children.isEmpty) {
return;
}
_OverlayEntryLocation? candidate = reversed ? children.last : children.first;
while (candidate != null) {
final _RenderDeferredLayoutBox? renderBox = candidate._overlayChildRenderBox;
candidate = reversed ? candidate.previous : candidate.next;
if (renderBox != null) {
yield renderBox;
}
}
}
@override
void initState() {
super.initState();
widget.entry._overlayEntryStateNotifier!.value = this;
_theater = context.findAncestorRenderObjectOfType<_RenderTheater>()!;
assert(_sortedTheaterSiblings == null);
}
@override
void didUpdateWidget(_OverlayEntryWidget oldWidget) {
super.didUpdateWidget(oldWidget);
// OverlayState's build method always returns a RenderObjectWidget _Theater,
// so it's safe to assume that state equality implies render object equality.
assert(oldWidget.entry == widget.entry);
if (oldWidget.overlayState != widget.overlayState) {
final _RenderTheater newTheater = context.findAncestorRenderObjectOfType<_RenderTheater>()!;
assert(_theater != newTheater);
_theater = newTheater;
}
}
@override
void dispose() {
widget.entry._overlayEntryStateNotifier?.value = null;
widget.entry._didUnmount();
_sortedTheaterSiblings = null;
super.dispose();
}
@override
Widget build(BuildContext context) {
return TickerMode(
enabled: widget.tickerEnabled,
child: _RenderTheaterMarker(
theater: _theater,
overlayEntryWidgetState: this,
// Use a Builder so that the `widget.entry.builder` can have access to
// _RenderTheaterMarker.of
child: Builder(builder: widget.entry.builder),
),
);
}
void _markNeedsBuild() {
setState(() {
/* the state that changed is in the builder */
});
}
}
/// A stack of entries that can be managed independently.
///
/// 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], [CupertinoApp] or a
/// [MaterialApp]. The navigator uses its overlay to manage the visual
/// appearance of its routes.
///
/// The [Overlay] widget uses a custom stack implementation, which is very
/// similar to the [Stack] widget. The main use case of [Overlay] is related to
/// navigation and being able to insert widgets on top of the pages in an app.
/// For layout purposes unrelated to navigation, consider using [Stack] instead.
///
/// An [Overlay] widget requires a [Directionality] widget to be in scope, so
/// that it can resolve direction-sensitive coordinates of any
/// [Positioned.directional] children.
///
/// For widgets drawn in an [OverlayEntry], do not assume that the size of the
/// [Overlay] is the size returned by [MediaQuery.sizeOf]. Nested overlays can
/// have different sizes.
///
/// {@tool dartpad}
/// This example shows how to use the [Overlay] to highlight the [NavigationBar]
/// destination.
///
/// ** See code in examples/api/lib/widgets/overlay/overlay.0.dart **
/// {@end-tool}
///
/// See also:
///
/// * [OverlayEntry], the class that is used for describing the overlay entries.
/// * [OverlayState], which is used to insert the entries into the overlay.
/// * [WidgetsApp], which inserts an [Overlay] widget indirectly via its [Navigator].
/// * [MaterialApp], which inserts an [Overlay] widget indirectly via its [Navigator].
/// * [CupertinoApp], which inserts an [Overlay] widget indirectly via its [Navigator].
/// * [Stack], which allows directly displaying a stack of widgets.
class Overlay extends StatefulWidget {
/// 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 is
/// created by the [Navigator] in a [WidgetsApp], [CupertinoApp], or a
/// [MaterialApp] for the application.
const Overlay({
super.key,
this.initialEntries = const <OverlayEntry>[],
this.clipBehavior = Clip.hardEdge,
this.alwaysSizeToContent = false,
});
/// Wrap the provided `child` in an [Overlay] to allow other visual elements
/// (packed in [OverlayEntry]s) to float on top of the child.
///
/// This is a convenience method over the regular [Overlay] constructor: It
/// creates an [Overlay] and puts the provided `child` in an [OverlayEntry]
/// at the bottom of that newly created Overlay.
static Widget wrap({
Key? key,
Clip clipBehavior = Clip.hardEdge,
bool alwaysSizeToContent = false,
required Widget child,
}) {
return _WrappingOverlay(
key: key,
clipBehavior: clipBehavior,
alwaysSizeToContent: alwaysSizeToContent,
child: child,
);
}
/// The entries to include in the overlay initially.
///
/// 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.insert] or
/// [OverlayState.insertAll].
///
/// To remove an entry from an [Overlay], use [OverlayEntry.remove].
final List<OverlayEntry> initialEntries;
/// {@macro flutter.material.Material.clipBehavior}
///
/// Defaults to [Clip.hardEdge].
final Clip clipBehavior;
/// Determines that the overlay should always size itself to content.
///
/// Normally overlay will only size itself to content if the incoming
/// constraints are infinite and there is a [OverlayEntry] that can size
/// the overlay. Setting this to `true` will force this behavior even for
/// finite (but possibly loose) constraints.
///
/// Setting this to true requires an [OverlayEntry] that can size the overlay
/// based on itself ([OverlayEntry.canSizeOverlay] set to true). If not provided
/// an exception is thrown.
final bool alwaysSizeToContent;
/// The [OverlayState] from the closest instance of [Overlay] that encloses
/// the given context within the closest [LookupBoundary], and, in debug mode,
/// will throw if one is not found.
///
/// In debug mode, if the `debugRequiredFor` argument is provided and an
/// overlay isn't found, then this function will throw an exception containing
/// the runtime type of the given widget in the error message. The exception
/// attempts to explain that the calling [Widget] (the one given by the
/// `debugRequiredFor` argument) needs an [Overlay] to be present to function.
/// If `debugRequiredFor` is not supplied, then the error message is more
/// generic.
///
/// Typical usage is as follows:
///
/// ```dart
/// OverlayState overlay = Overlay.of(context);
/// ```
///
/// {@template flutter.widgets.Overlay.of}
/// 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].
/// {@endtemplate}
///
/// See also:
///
/// * [Overlay.maybeOf] for a similar function that returns null if an
/// [Overlay] is not found.
static OverlayState of(
BuildContext context, {
bool rootOverlay = false,
Widget? debugRequiredFor,
}) {
final OverlayState? result = maybeOf(context, rootOverlay: rootOverlay);
assert(() {
if (result == null) {
final bool hiddenByBoundary = LookupBoundary.debugIsHidingAncestorStateOfType<OverlayState>(
context,
);
final information = <DiagnosticsNode>[
ErrorSummary(
'No Overlay widget found${hiddenByBoundary ? ' within the closest LookupBoundary' : ''}.',
),
if (hiddenByBoundary)
ErrorDescription(
'There is an ancestor Overlay widget, but it is hidden by a LookupBoundary.',
),
ErrorDescription(
'${debugRequiredFor?.runtimeType ?? 'Some'} 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, CupertinoApp or Navigator widget in the runApp() call.',
),
if (debugRequiredFor != null)
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);
}
return true;
}());
return result!;
}
/// The [OverlayState] from the closest instance of [Overlay] that encloses
/// the given context within the closest [LookupBoundary], if any.
///
/// Typical usage is as follows:
///
/// ```dart
/// OverlayState? overlay = Overlay.maybeOf(context);
/// ```
///
/// {@macro flutter.widgets.Overlay.of}
///
/// See also:
///
/// * [Overlay.of] for a similar function that returns a non-nullable result
/// and throws if an [Overlay] is not found.
static OverlayState? maybeOf(BuildContext context, {bool rootOverlay = false}) {
return _RenderTheaterMarker.maybeOf(
context,
targetRootOverlay: rootOverlay,
createDependency: false,
)?.overlayEntryWidgetState.widget.overlayState;
}
@override
OverlayState createState() => OverlayState();
}
/// The current state of an [Overlay].
///
/// Used to insert [OverlayEntry]s into the overlay using the [insert] and
/// [insertAll] functions.
class OverlayState extends State<Overlay> with TickerProviderStateMixin {
final List<OverlayEntry> _entries = <OverlayEntry>[];
@protected
@override
void initState() {
super.initState();
insertAll(widget.initialEntries);
}
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;
}
bool _debugCanInsertEntry(OverlayEntry entry) {
final operandsInformation = <DiagnosticsNode>[
DiagnosticsProperty<OverlayEntry>(
'The OverlayEntry was',
entry,
style: DiagnosticsTreeStyle.errorProperty,
),
DiagnosticsProperty<OverlayState>(
'The Overlay the OverlayEntry was trying to insert to was',
this,
style: DiagnosticsTreeStyle.errorProperty,
),
];
if (!mounted) {
throw FlutterError.fromParts(<DiagnosticsNode>[
ErrorSummary('Attempted to insert an OverlayEntry to an already disposed Overlay.'),
...operandsInformation,
]);
}
final OverlayState? currentOverlay = entry._overlay;
final bool alreadyContainsEntry = _entries.contains(entry);
if (alreadyContainsEntry) {
final bool inconsistentOverlayState = !identical(currentOverlay, this);
throw FlutterError.fromParts(<DiagnosticsNode>[
ErrorSummary('The specified entry is already present in the target Overlay.'),
...operandsInformation,
if (inconsistentOverlayState)
ErrorHint('This could be an error in the Flutter framework.')
else
ErrorHint(
'Consider calling remove on the OverlayEntry before inserting it to a different Overlay, '
'or switching to the OverlayPortal API to avoid manual OverlayEntry management.',
),
if (inconsistentOverlayState)
DiagnosticsProperty<OverlayState>(
"The OverlayEntry's current Overlay was",
currentOverlay,
style: DiagnosticsTreeStyle.errorProperty,
),
]);
}
if (currentOverlay == null) {
return true;
}
throw FlutterError.fromParts(<DiagnosticsNode>[
ErrorSummary('The specified entry is already present in a different Overlay.'),
...operandsInformation,
DiagnosticsProperty<OverlayState>(
"The OverlayEntry's current Overlay was",
currentOverlay,
style: DiagnosticsTreeStyle.errorProperty,
),
ErrorHint(
'Consider calling remove on the OverlayEntry before inserting it to a different Overlay, '
'or switching to the OverlayPortal API to avoid manual OverlayEntry management.',
),
]);
}
/// Insert the given entry into the overlay.
///
/// If `below` is non-null, the entry is inserted just below `below`.
/// If `above` is non-null, the entry is inserted just above `above`.
/// Otherwise, the entry is inserted on top.
///
/// It is an error to specify both `above` and `below`.
void insert(OverlayEntry entry, {OverlayEntry? below, OverlayEntry? above}) {
assert(_debugVerifyInsertPosition(above, below));
assert(_debugCanInsertEntry(entry));
entry._overlay = this;
setState(() {
_entries.insert(_insertionIndex(below, above), entry);
});
}
/// Insert all the entries in the given iterable.
///
/// If `below` is non-null, the entries are inserted just below `below`.
/// If `above` is non-null, the entries are inserted just above `above`.
/// Otherwise, the entries are inserted on top.
///
/// It is an error to specify both `above` and `below`.
void insertAll(Iterable<OverlayEntry> entries, {OverlayEntry? below, OverlayEntry? above}) {
assert(_debugVerifyInsertPosition(above, below));
assert(entries.every(_debugCanInsertEntry));
if (entries.isEmpty) {
return;
}
for (final entry in entries) {
assert(entry._overlay == null);
entry._overlay = this;
}
setState(() {
_entries.insertAll(_insertionIndex(below, above), entries);
});
}
bool _debugVerifyInsertPosition(
OverlayEntry? above,
OverlayEntry? below, {
Iterable<OverlayEntry>? newEntries,
}) {
assert(above == null || below == null, 'Only one of `above` and `below` may be specified.');
assert(
above == null ||
(above._overlay == this &&
_entries.contains(above) &&
(newEntries?.contains(above) ?? true)),
'The provided entry used for `above` must be present in the Overlay${newEntries != null ? ' and in the `newEntriesList`' : ''}.',
);
assert(
below == null ||
(below._overlay == this &&
_entries.contains(below) &&
(newEntries?.contains(below) ?? true)),
'The provided entry used for `below` must be present in the Overlay${newEntries != null ? ' and in the `newEntriesList`' : ''}.',
);
return true;
}
/// 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(_debugVerifyInsertPosition(above, below, newEntries: 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 old = LinkedHashSet<OverlayEntry>.of(_entries);
for (final entry in newEntriesList) {
entry._overlay ??= this;
}
setState(() {
_entries.clear();
_entries.addAll(newEntriesList);
old.removeAll(newEntriesList);
_entries.insertAll(_insertionIndex(below, above), old);
});
}
void _markDirty() {
if (mounted) {
setState(() {});
}
}
/// (DEBUG ONLY) Check whether a given entry is visible (i.e., not behind an
/// opaque entry).
///
/// 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 debug mode, and always returns false in release mode.
bool debugIsVisible(OverlayEntry entry) {
var result = false;
assert(_entries.contains(entry));
assert(() {
for (int i = _entries.length - 1; i > 0; i -= 1) {
final OverlayEntry candidate = _entries[i];
if (candidate == entry) {
result = true;
break;
}
if (candidate.opaque) {
break;
}
}
return true;
}());
return result;
}
void _didChangeEntryOpacity() {
setState(() {
// We use the opacity of the entry in our build function, which means we
// our state has changed.
});
}
@protected
@override
Widget build(BuildContext context) {
// This list is filled backwards and then reversed below before
// it is added to the tree.
final children = <_OverlayEntryWidget>[];
var onstage = true;
var onstageCount = 0;
for (final OverlayEntry entry in _entries.reversed) {
if (onstage) {
onstageCount += 1;
children.add(_OverlayEntryWidget(key: entry._key, overlayState: this, entry: entry));
if (entry.opaque) {
onstage = false;
}
} else if (entry.maintainState) {
children.add(
_OverlayEntryWidget(
key: entry._key,
overlayState: this,
entry: entry,
tickerEnabled: false,
),
);
}
}
return _Theater(
skipCount: children.length - onstageCount,
clipBehavior: widget.clipBehavior,
alwaysSizeToContent: widget.alwaysSizeToContent,
children: children.reversed.toList(growable: false),
);
}
@protected
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
// TODO(jacobr): use IterableProperty instead as that would
// provide a slightly more consistent string summary of the List.
properties.add(DiagnosticsProperty<List<OverlayEntry>>('entries', _entries));
}
}
class _WrappingOverlay extends StatefulWidget {
const _WrappingOverlay({
super.key,
this.clipBehavior = Clip.hardEdge,
required this.alwaysSizeToContent,
required this.child,
});
final Clip clipBehavior;
final bool alwaysSizeToContent;
final Widget child;
@override
State<_WrappingOverlay> createState() => _WrappingOverlayState();
}
class _WrappingOverlayState extends State<_WrappingOverlay> {
late final OverlayEntry _entry = OverlayEntry(
canSizeOverlay: true,
opaque: true,
builder: (BuildContext context) {
return widget.child;
},
);
@override
void didUpdateWidget(_WrappingOverlay oldWidget) {
super.didUpdateWidget(oldWidget);
_entry.markNeedsBuild();
}
@override
void dispose() {
_entry
..remove()
..dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Overlay(
clipBehavior: widget.clipBehavior,
alwaysSizeToContent: widget.alwaysSizeToContent,
initialEntries: <OverlayEntry>[_entry],
);
}
}
/// Special version of a [Stack], that doesn't layout and render the first
/// [skipCount] children.
///
/// The first [skipCount] children are considered "offstage".
class _Theater extends MultiChildRenderObjectWidget {
const _Theater({
this.skipCount = 0,
this.clipBehavior = Clip.hardEdge,
required this.alwaysSizeToContent,
required List<_OverlayEntryWidget> super.children,
}) : assert(skipCount >= 0),
assert(children.length >= skipCount);
final int skipCount;
final Clip clipBehavior;
final bool alwaysSizeToContent;
@override
_TheaterElement createElement() => _TheaterElement(this);