This repository has been archived by the owner on Feb 22, 2023. It is now read-only.
/
menu_anchor.dart
3820 lines (3503 loc) · 134 KB
/
menu_anchor.dart
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.
import 'dart:math' as math;
import 'package:flutter/foundation.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'button_style.dart';
import 'button_style_button.dart';
import 'checkbox.dart';
import 'color_scheme.dart';
import 'colors.dart';
import 'constants.dart';
import 'icons.dart';
import 'ink_well.dart';
import 'material.dart';
import 'material_localizations.dart';
import 'material_state.dart';
import 'menu_bar_theme.dart';
import 'menu_button_theme.dart';
import 'menu_style.dart';
import 'menu_theme.dart';
import 'radio.dart';
import 'text_button.dart';
import 'theme.dart';
import 'theme_data.dart';
// Examples can assume:
// bool _throwShotAway = false;
// late BuildContext context;
// enum SingingCharacter { lafayette }
// late SingingCharacter? _character;
// late StateSetter setState;
// Enable if you want verbose logging about menu changes.
const bool _kDebugMenus = false;
// The default size of the arrow in _MenuItemLabel that indicates that a menu
// has a submenu.
const double _kDefaultSubmenuIconSize = 24;
// The default spacing between the the leading icon, label, trailing icon, and
// shortcut label in a _MenuItemLabel.
const double _kLabelItemDefaultSpacing = 12;
// The minimum spacing between the the leading icon, label, trailing icon, and
// shortcut label in a _MenuItemLabel.
const double _kLabelItemMinSpacing = 4;
// Navigation shortcuts that we need to make sure are active when menus are
// open.
const Map<ShortcutActivator, Intent> _kMenuTraversalShortcuts = <ShortcutActivator, Intent>{
SingleActivator(LogicalKeyboardKey.gameButtonA): ActivateIntent(),
SingleActivator(LogicalKeyboardKey.escape): DismissIntent(),
SingleActivator(LogicalKeyboardKey.tab): NextFocusIntent(),
SingleActivator(LogicalKeyboardKey.tab, shift: true): PreviousFocusIntent(),
SingleActivator(LogicalKeyboardKey.arrowDown): DirectionalFocusIntent(TraversalDirection.down),
SingleActivator(LogicalKeyboardKey.arrowUp): DirectionalFocusIntent(TraversalDirection.up),
SingleActivator(LogicalKeyboardKey.arrowLeft): DirectionalFocusIntent(TraversalDirection.left),
SingleActivator(LogicalKeyboardKey.arrowRight): DirectionalFocusIntent(TraversalDirection.right),
};
// The minimum vertical spacing on the outside of menus.
const double _kMenuVerticalMinPadding = 8;
// How close to the edge of the safe area the menu will be placed.
const double _kMenuViewPadding = 8;
// The minimum horizontal spacing on the outside of the top level menu.
const double _kTopLevelMenuHorizontalMinPadding = 4;
/// The type of builder function used by [MenuAnchor.builder] to build the
/// widget that the [MenuAnchor] surrounds.
///
/// The `context` is the context that the widget is being built in.
///
/// The `controller` is the [MenuController] that can be used to open and close
/// the menu with.
///
/// The `child` is an optional child supplied as the [MenuAnchor.child]
/// attribute. The child is intended to be incorporated in the result of the
/// function.
typedef MenuAnchorChildBuilder = Widget Function(
BuildContext context,
MenuController controller,
Widget? child,
);
/// A widget used to mark the "anchor" for a set of submenus, defining the
/// rectangle used to position the menu, which can be done either with an
/// explicit location, or with an alignment.
///
/// When creating a menu with [MenuBar] or a [SubmenuButton], a [MenuAnchor] is
/// not needed, since they provide their own internally.
///
/// The [MenuAnchor] is meant to be a slightly lower level interface than
/// [MenuBar], used in situations where a [MenuBar] isn't appropriate, or to
/// construct widgets or screen regions that have submenus.
///
/// {@tool dartpad}
/// This example shows how to use a [MenuAnchor] to wrap a button and open a
/// cascading menu from the button.
///
/// ** See code in examples/api/lib/material/menu_anchor/menu_anchor.0.dart **
/// {@end-tool}
///
/// {@tool dartpad}
/// This example shows how to use a [MenuAnchor] to create a cascading context
/// menu in a region of the view, positioned where the user clicks the mouse
/// with Ctrl pressed. The [anchorTapClosesMenu] attribute is set to true so
/// that clicks on the [MenuAnchor] area will cause the menus to be closed.
///
/// ** See code in examples/api/lib/material/menu_anchor/menu_anchor.1.dart **
/// {@end-tool}
class MenuAnchor extends StatefulWidget {
/// Creates a const [MenuAnchor].
///
/// The [menuChildren] argument is required.
const MenuAnchor({
super.key,
this.controller,
this.childFocusNode,
this.style,
this.alignmentOffset = Offset.zero,
this.clipBehavior = Clip.none,
this.anchorTapClosesMenu = false,
this.onOpen,
this.onClose,
this.crossAxisUnconstrained = true,
required this.menuChildren,
this.builder,
this.child,
});
/// An optional controller that allows opening and closing of the menu from
/// other widgets.
final MenuController? controller;
/// The [childFocusNode] attribute is the optional [FocusNode] also associated
/// the [child] or [builder] widget that opens the menu.
///
/// The focus node should be attached to the widget that should receive focus
/// if keyboard focus traversal moves the focus off of the submenu with the
/// arrow keys.
///
/// If not supplied, then keyboard traversal from the menu back to the
/// controlling button when the menu is open is disabled.
final FocusNode? childFocusNode;
/// The [MenuStyle] that defines the visual attributes of the menu bar.
///
/// Colors and sizing of the menus is controllable via the [MenuStyle].
///
/// Defaults to the ambient [MenuThemeData.style].
final MenuStyle? style;
/// The offset of the menu relative to the alignment origin determined by
/// [MenuStyle.alignment] on the [style] attribute and the ambient
/// [Directionality].
///
/// Use this for adjustments of the menu placement.
///
/// Increasing [Offset.dy] values of [alignmentOffset] move the menu position
/// down.
///
/// If the [MenuStyle.alignment] from [style] is not an [AlignmentDirectional]
/// (e.g. [Alignment]), then increasing [Offset.dx] values of
/// [alignmentOffset] move the menu position to the right.
///
/// If the [MenuStyle.alignment] from [style] is an [AlignmentDirectional],
/// then in a [TextDirection.ltr] [Directionality], increasing [Offset.dx]
/// values of [alignmentOffset] move the menu position to the right. In a
/// [TextDirection.rtl] directionality, increasing [Offset.dx] values of
/// [alignmentOffset] move the menu position to the left.
///
/// Defaults to [Offset.zero].
final Offset? alignmentOffset;
/// {@macro flutter.material.Material.clipBehavior}
///
/// Defaults to [Clip.none].
final Clip clipBehavior;
/// Whether the menus will be closed if the anchor area is tapped.
///
/// For menus opened by buttons that toggle the menu, if the button is tapped
/// when the menu is open, the button should close the menu. But if
/// [anchorTapClosesMenu] is true, then the menu will close, and
/// (surprisingly) immediately re-open. This is because tapping on the button
/// closes the menu before the `onPressed` or `onTap` handler is called
/// because of it being considered to be "outside" the menu system, and then
/// the button (seeing that the menu is closed) immediately reopens the menu.
/// The result is that the user thinks that tapping on the button does
/// nothing. So, for button-initiated menus, this value is typically false so
/// that the menu anchor area is considered "inside" of the menu system and
/// doesn't cause it to close unless [MenuController.close] is called.
///
/// For menus that are positioned using [MenuController.open]'s `position`
/// parameter, it is often desirable that clicking on the anchor always closes
/// the menu since the anchor area isn't usually considered part of the menu
/// system by the user. In this case [anchorTapClosesMenu] should be true.
///
/// Defaults to false.
final bool anchorTapClosesMenu;
/// A callback that is invoked when the menu is opened.
final VoidCallback? onOpen;
/// A callback that is invoked when the menu is closed.
final VoidCallback? onClose;
/// Determine if the menu panel can be wrapped by a [UnconstrainedBox] which allows
/// the panel to render at its "natural" size.
///
/// Defaults to true as it allows developers to render the menu panel at the
/// size it should be. When it is set to false, it can be useful when the menu should
/// be constrained in both main axis and cross axis, such as a [DropdownMenu].
final bool crossAxisUnconstrained;
/// A list of children containing the menu items that are the contents of the
/// menu surrounded by this [MenuAnchor].
///
/// {@macro flutter.material.MenuBar.shortcuts_note}
final List<Widget> menuChildren;
/// The widget that this [MenuAnchor] surrounds.
///
/// Typically this is a button used to open the menu by calling
/// [MenuController.open] on the `controller` passed to the builder.
///
/// If not supplied, then the [MenuAnchor] will be the size that its parent
/// allocates for it.
final MenuAnchorChildBuilder? builder;
/// The optional child to be passed to the [builder].
///
/// Supply this child if there is a portion of the widget tree built in
/// [builder] that doesn't depend on the `controller` or `context` supplied to
/// the [builder]. It will be more efficient, since Flutter doesn't then need
/// to rebuild this child when those change.
final Widget? child;
@override
State<MenuAnchor> createState() => _MenuAnchorState();
@override
List<DiagnosticsNode> debugDescribeChildren() {
return menuChildren.map<DiagnosticsNode>((Widget child) => child.toDiagnosticsNode()).toList();
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(FlagProperty('anchorTapClosesMenu', value: anchorTapClosesMenu, ifTrue: 'AUTO-CLOSE'));
properties.add(DiagnosticsProperty<FocusNode?>('focusNode', childFocusNode));
properties.add(DiagnosticsProperty<MenuStyle?>('style', style));
properties.add(EnumProperty<Clip>('clipBehavior', clipBehavior));
properties.add(DiagnosticsProperty<Offset?>('alignmentOffset', alignmentOffset));
properties.add(StringProperty('child', child.toString()));
}
}
class _MenuAnchorState extends State<MenuAnchor> {
// This is the global key that is used later to determine the bounding rect
// for the anchor's region that the CustomSingleChildLayout's delegate
// uses to determine where to place the menu on the screen and to avoid the
// view's edges.
final GlobalKey _anchorKey = GlobalKey(debugLabel: kReleaseMode ? null : 'MenuAnchor');
_MenuAnchorState? _parent;
final FocusScopeNode _menuScopeNode = FocusScopeNode(debugLabel: kReleaseMode ? null : 'MenuAnchor sub menu');
MenuController? _internalMenuController;
final List<_MenuAnchorState> _anchorChildren = <_MenuAnchorState>[];
ScrollPosition? _position;
Size? _viewSize;
OverlayEntry? _overlayEntry;
Axis get _orientation => Axis.vertical;
bool get _isOpen => _overlayEntry != null;
bool get _isRoot => _parent == null;
bool get _isTopLevel => _parent?._isRoot ?? false;
MenuController get _menuController => widget.controller ?? _internalMenuController!;
@override
void initState() {
super.initState();
if (widget.controller == null) {
_internalMenuController = MenuController();
}
_menuController._attach(this);
}
@override
void dispose() {
assert(_debugMenuInfo('Disposing of $this'));
if (_isOpen) {
_close(inDispose: true);
_parent?._removeChild(this);
}
_anchorChildren.clear();
_menuController._detach(this);
_internalMenuController = null;
super.dispose();
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
_parent?._removeChild(this);
_parent = _MenuAnchorState._maybeOf(context);
_parent?._addChild(this);
_position?.isScrollingNotifier.removeListener(_handleScroll);
_position = Scrollable.maybeOf(context)?.position;
_position?.isScrollingNotifier.addListener(_handleScroll);
final Size newSize = MediaQuery.sizeOf(context);
if (_viewSize != null && newSize != _viewSize) {
// Close the menus if the view changes size.
_root._close();
}
_viewSize = newSize;
}
@override
void didUpdateWidget(MenuAnchor oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.controller != widget.controller) {
oldWidget.controller?._detach(this);
if (widget.controller != null) {
_internalMenuController?._detach(this);
_internalMenuController = null;
widget.controller?._attach(this);
} else {
assert(_internalMenuController == null);
_internalMenuController = MenuController().._attach(this);
}
}
assert(_menuController._anchor == this);
if (_overlayEntry != null) {
// Needs to update the overlay entry on the next frame, since it's in the
// overlay.
SchedulerBinding.instance.addPostFrameCallback((Duration _) {
_overlayEntry!.markNeedsBuild();
});
}
}
@override
Widget build(BuildContext context) {
Widget child = _buildContents(context);
if (!widget.anchorTapClosesMenu) {
child = TapRegion(
groupId: _root,
onTapOutside: (PointerDownEvent event) {
assert(_debugMenuInfo('Tapped Outside ${widget.controller}'));
_closeChildren();
},
child: child,
);
}
return _MenuAnchorMarker(
anchorKey: _anchorKey,
anchor: this,
isOpen: _isOpen,
child: child,
);
}
Widget _buildContents(BuildContext context) {
return Builder(
key: _anchorKey,
builder: (BuildContext context) {
if (widget.builder == null) {
return widget.child ?? const SizedBox();
}
return widget.builder!(
context,
_menuController,
widget.child,
);
},
);
}
// Returns the first focusable item in the submenu, where "first" is
// determined by the focus traversal policy.
FocusNode? get _firstItemFocusNode {
if (_menuScopeNode.context == null) {
return null;
}
final FocusTraversalPolicy policy =
FocusTraversalGroup.maybeOf(_menuScopeNode.context!) ?? ReadingOrderTraversalPolicy();
return policy.findFirstFocus(_menuScopeNode, ignoreCurrentFocus: true);
}
void _addChild(_MenuAnchorState child) {
assert(_isRoot || _debugMenuInfo('Added root child: $child'));
assert(!_anchorChildren.contains(child));
_anchorChildren.add(child);
assert(_debugMenuInfo('Tree:\n${widget.toStringDeep()}'));
}
void _removeChild(_MenuAnchorState child) {
assert(_isRoot || _debugMenuInfo('Removed root child: $child'));
assert(_anchorChildren.contains(child));
_anchorChildren.remove(child);
assert(_debugMenuInfo('Tree:\n${widget.toStringDeep()}'));
}
_MenuAnchorState? get _nextSibling {
final int index = _parent!._anchorChildren.indexOf(this);
assert(index != -1, 'Unable to find this widget $this in parent $_parent');
if (index < _parent!._anchorChildren.length - 1) {
return _parent!._anchorChildren[index + 1];
}
return null;
}
_MenuAnchorState? get _previousSibling {
final int index = _parent!._anchorChildren.indexOf(this);
assert(index != -1, 'Unable to find this widget $this in parent $_parent');
if (index > 0) {
return _parent!._anchorChildren[index - 1];
}
return null;
}
_MenuAnchorState get _root {
_MenuAnchorState anchor = this;
while (anchor._parent != null) {
anchor = anchor._parent!;
}
return anchor;
}
_MenuAnchorState get _topLevel {
_MenuAnchorState handle = this;
while (handle._parent!._isTopLevel) {
handle = handle._parent!;
}
return handle;
}
void _childChangedOpenState() {
if (mounted) {
_parent?._childChangedOpenState();
setState(() {
// Mark dirty, but only if mounted.
});
}
}
void _focusButton() {
if (widget.childFocusNode == null) {
return;
}
assert(_debugMenuInfo('Requesting focus for ${widget.childFocusNode}'));
widget.childFocusNode!.requestFocus();
}
void _handleScroll() {
// If an ancestor scrolls, and we're a top level or root anchor, then close
// the menus. Don't just close it on *any* scroll, since we want to be able
// to scroll menus themselves if they're too big for the view.
if (_isTopLevel || _isRoot) {
_root._close();
}
}
/// Open the menu, optionally at a position relative to the [MenuAnchor].
///
/// Call this when the menu should be shown to the user.
///
/// The optional `position` argument will specify the location of the menu in
/// the local coordinates of the [MenuAnchor], ignoring any
/// [MenuStyle.alignment] and/or [MenuAnchor.alignmentOffset] that were
/// specified.
void _open({Offset? position}) {
assert(_menuController._anchor == this);
if (_isOpen && position == null) {
assert(_debugMenuInfo("Not opening $this because it's already open"));
return;
}
if (_isOpen && position != null) {
// The menu is already open, but we need to move to another location, so
// close it first.
_close();
}
assert(_debugMenuInfo(
'Opening $this at ${position ?? Offset.zero} with alignment offset ${widget.alignmentOffset ?? Offset.zero}'));
_parent?._closeChildren(); // Close all siblings.
assert(_overlayEntry == null);
final BuildContext outerContext = context;
_parent?._childChangedOpenState();
setState(() {
_overlayEntry = OverlayEntry(
builder: (BuildContext context) {
final OverlayState overlay = Overlay.of(outerContext);
return Positioned.directional(
textDirection: Directionality.of(outerContext),
top: 0,
start: 0,
child: Directionality(
textDirection: Directionality.of(outerContext),
child: InheritedTheme.captureAll(
// Copy all the themes from the supplied outer context to the
// overlay.
outerContext,
_MenuAnchorMarker(
// Re-advertize the anchor here in the overlay, since
// otherwise a search for the anchor by descendants won't find
// it.
anchorKey: _anchorKey,
anchor: this,
isOpen: _isOpen,
child: _Submenu(
anchor: this,
menuStyle: widget.style,
alignmentOffset: widget.alignmentOffset ?? Offset.zero,
menuPosition: position,
clipBehavior: widget.clipBehavior,
menuChildren: widget.menuChildren,
crossAxisUnconstrained: widget.crossAxisUnconstrained,
),
),
to: overlay.context,
),
),
);
},
);
});
Overlay.of(context).insert(_overlayEntry!);
widget.onOpen?.call();
}
/// Close the menu.
///
/// Call this when the menu should be closed. Has no effect if the menu is
/// already closed.
void _close({bool inDispose = false}) {
assert(_debugMenuInfo('Closing $this'));
if (!_isOpen) {
return;
}
_closeChildren(inDispose: inDispose);
_overlayEntry?.remove();
_overlayEntry = null;
if (!inDispose) {
// Notify that _childIsOpen changed state, but only if not
// currently disposing.
_parent?._childChangedOpenState();
}
widget.onClose?.call();
}
void _closeChildren({bool inDispose = false}) {
assert(_debugMenuInfo('Closing children of $this${inDispose ? ' (dispose)' : ''}'));
for (final _MenuAnchorState child in List<_MenuAnchorState>.from(_anchorChildren)) {
child._close(inDispose: inDispose);
}
}
// Returns the active anchor in the given context, if any, and creates a
// dependency relationship that will rebuild the context when the node
// changes.
static _MenuAnchorState? _maybeOf(BuildContext context) {
return context.dependOnInheritedWidgetOfExactType<_MenuAnchorMarker>()?.anchor;
}
}
/// A controller to manage a menu created by a [MenuBar] or [MenuAnchor].
///
/// A [MenuController] is used to control and interrogate a menu after it has
/// been created, with methods such as [open] and [close], and state accessors
/// like [isOpen].
///
/// See also:
///
/// * [MenuAnchor], a widget that defines a region that has submenu.
/// * [MenuBar], a widget that creates a menu bar, that can take an optional
/// [MenuController].
/// * [SubmenuButton], a widget that has a button that manages a submenu.
class MenuController {
/// The anchor that this controller controls.
///
/// This is set automatically when a [MenuController] is given to the anchor
/// it controls.
_MenuAnchorState? _anchor;
/// Whether or not the associated menu is currently open.
bool get isOpen {
assert(_anchor != null);
return _anchor!._isOpen;
}
/// Close the menu that this menu controller is associated with.
///
/// Associating with a menu is done by passing a [MenuController] to a
/// [MenuAnchor]. A [MenuController] is also be received by the
/// [MenuAnchor.builder] when invoked.
///
/// If the menu's anchor point (either a [MenuBar] or a [MenuAnchor]) is
/// scrolled by an ancestor, or the view changes size, then any open menu will
/// automatically close.
void close() {
assert(_anchor != null);
_anchor!._close();
}
/// Opens the menu that this menu controller is associated with.
///
/// If `position` is given, then the menu will open at the position given, in
/// the coordinate space of the [MenuAnchor] this controller is attached to.
///
/// If given, the `position` will override the [MenuAnchor.alignmentOffset]
/// given to the [MenuAnchor].
///
/// If the menu's anchor point (either a [MenuBar] or a [MenuAnchor]) is
/// scrolled by an ancestor, or the view changes size, then any open menu will
/// automatically close.
void open({Offset? position}) {
assert(_anchor != null);
_anchor!._open(position: position);
}
// ignore: use_setters_to_change_properties
void _attach(_MenuAnchorState anchor) {
_anchor = anchor;
}
void _detach(_MenuAnchorState anchor) {
if (_anchor == anchor) {
_anchor = null;
}
}
}
/// A menu bar that manages cascading child menus.
///
/// This is a Material Design menu bar that typically resides above the main
/// body of an application (but can go anywhere) that defines a menu system for
/// invoking callbacks in response to user selection of a menu item.
///
/// The menus can be opened with a click or tap. Once a menu is opened, it can
/// be navigated by using the arrow and tab keys or via mouse hover. Selecting a
/// menu item can be done by pressing enter, or by clicking or tapping on the
/// menu item. Clicking or tapping on any part of the user interface that isn't
/// part of the menu system controlled by the same controller will cause all of
/// the menus controlled by that controller to close, as will pressing the
/// escape key.
///
/// When a menu item with a submenu is clicked on, it toggles the visibility of
/// the submenu. When the menu item is hovered over, the submenu will open, and
/// hovering over other items will close the previous menu and open the newly
/// hovered one. When those open/close transitions occur,
/// [SubmenuButton.onOpen], and [SubmenuButton.onClose] are called on the
/// corresponding [SubmenuButton] child of the menu bar.
///
/// {@template flutter.material.MenuBar.shortcuts_note}
/// Menus using [MenuItemButton] can have a [SingleActivator] or
/// [CharacterActivator] assigned to them as their [MenuItemButton.shortcut],
/// which will display an appropriate shortcut hint. Even though the shortcut
/// labels are displayed in the menu, shortcuts are not automatically handled.
/// They must be available in whatever context they are appropriate, and handled
/// via another mechanism.
///
/// If shortcuts should be generally enabled, but are not easily defined in a
/// context surrounding the menu bar, consider registering them with a
/// [ShortcutRegistry] (one is already included in the [WidgetsApp], and thus
/// also [MaterialApp] and [CupertinoApp]), as shown in the example below. To be
/// sure that selecting a menu item and triggering the shortcut do the same
/// thing, it is recommended that they call the same callback.
///
/// {@tool dartpad} This example shows a [MenuBar] that contains a single top
/// level menu, containing three items: "About", a checkbox menu item for
/// showing a message, and "Quit". The items are identified with an enum value,
/// and the shortcuts are registered globally with the [ShortcutRegistry].
///
/// ** See code in examples/api/lib/material/menu_anchor/menu_bar.0.dart **
/// {@end-tool}
/// {@endtemplate}
///
/// {@macro flutter.material.MenuAcceleratorLabel.accelerator_sample}
///
/// See also:
///
/// * [MenuAnchor], a widget that creates a region with a submenu and shows it
/// when requested.
/// * [SubmenuButton], a menu item which manages a submenu.
/// * [MenuItemButton], a leaf menu item which displays the label, an optional
/// shortcut label, and optional leading and trailing icons.
/// * [PlatformMenuBar], which creates a menu bar that is rendered by the host
/// platform instead of by Flutter (on macOS, for example).
/// * [ShortcutRegistry], a registry of shortcuts that apply for the entire
/// application.
/// * [VoidCallbackIntent], to define intents that will call a [VoidCallback] and
/// work with the [Actions] and [Shortcuts] system.
/// * [CallbackShortcuts], to define shortcuts that call a callback without
/// involving [Actions].
class MenuBar extends StatelessWidget {
/// Creates a const [MenuBar].
///
/// The [children] argument is required.
const MenuBar({
super.key,
this.style,
this.clipBehavior = Clip.none,
this.controller,
required this.children,
});
/// The [MenuStyle] that defines the visual attributes of the menu bar.
///
/// Colors and sizing of the menus is controllable via the [MenuStyle].
///
/// Defaults to the ambient [MenuThemeData.style].
final MenuStyle? style;
/// {@macro flutter.material.Material.clipBehavior}
///
/// Defaults to [Clip.none].
final Clip clipBehavior;
/// The [MenuController] to use for this menu bar.
final MenuController? controller;
/// The list of menu items that are the top level children of the [MenuBar].
///
/// A Widget in Flutter is immutable, so directly modifying the [children]
/// with [List] APIs such as `someMenuBarWidget.menus.add(...)` will result in
/// incorrect behaviors. Whenever the menus list is modified, a new list
/// object must be provided.
///
/// {@macro flutter.material.MenuBar.shortcuts_note}
final List<Widget> children;
@override
Widget build(BuildContext context) {
assert(debugCheckHasOverlay(context));
return _MenuBarAnchor(
controller: controller,
clipBehavior: clipBehavior,
style: style,
menuChildren: children,
);
}
@override
List<DiagnosticsNode> debugDescribeChildren() {
return <DiagnosticsNode>[
...children.map<DiagnosticsNode>(
(Widget item) => item.toDiagnosticsNode(),
),
];
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DiagnosticsProperty<MenuStyle?>('style', style, defaultValue: null));
properties.add(DiagnosticsProperty<Clip>('clipBehavior', clipBehavior, defaultValue: null));
}
}
/// A button for use in a [MenuBar], in a menu created with [MenuAnchor], or on
/// its own, that can be activated by click or keyboard navigation.
///
/// This widget represents a leaf entry in a menu hierarchy that is typically
/// part of a [MenuBar], but may be used independently, or as part of a menu
/// created with a [MenuAnchor].
///
/// {@macro flutter.material.MenuBar.shortcuts_note}
///
/// See also:
///
/// * [MenuBar], a class that creates a top level menu bar in a Material Design
/// style.
/// * [MenuAnchor], a widget that creates a region with a submenu and shows it
/// when requested.
/// * [SubmenuButton], a menu item similar to this one which manages a submenu.
/// * [PlatformMenuBar], which creates a menu bar that is rendered by the host
/// platform instead of by Flutter (on macOS, for example).
/// * [ShortcutRegistry], a registry of shortcuts that apply for the entire
/// application.
/// * [VoidCallbackIntent], to define intents that will call a [VoidCallback] and
/// work with the [Actions] and [Shortcuts] system.
/// * [CallbackShortcuts] to define shortcuts that call a callback without
/// involving [Actions].
class MenuItemButton extends StatefulWidget {
/// Creates a const [MenuItemButton].
///
/// The [child] attribute is required.
const MenuItemButton({
super.key,
this.onPressed,
this.onHover,
this.requestFocusOnHover = true,
this.onFocusChange,
this.focusNode,
this.shortcut,
this.style,
this.statesController,
this.clipBehavior = Clip.none,
this.leadingIcon,
this.trailingIcon,
required this.child,
});
/// Called when the button is tapped or otherwise activated.
///
/// If this callback is null, then the button will be disabled.
///
/// See also:
///
/// * [enabled], which is true if the button is enabled.
final VoidCallback? onPressed;
/// Called when a pointer enters or exits the button response area.
///
/// The value passed to the callback is true if a pointer has entered button
/// area and false if a pointer has exited.
final ValueChanged<bool>? onHover;
/// Determine if hovering can request focus.
///
/// Defaults to true.
final bool requestFocusOnHover;
/// Handler called when the focus changes.
///
/// Called with true if this widget's node gains focus, and false if it loses
/// focus.
final ValueChanged<bool>? onFocusChange;
/// {@macro flutter.widgets.Focus.focusNode}
final FocusNode? focusNode;
/// The optional shortcut that selects this [MenuItemButton].
///
/// {@macro flutter.material.MenuBar.shortcuts_note}
final MenuSerializableShortcut? shortcut;
/// Customizes this button's appearance.
///
/// Non-null properties of this style override the corresponding properties in
/// [themeStyleOf] and [defaultStyleOf]. [MaterialStateProperty]s that resolve
/// to non-null values will similarly override the corresponding
/// [MaterialStateProperty]s in [themeStyleOf] and [defaultStyleOf].
///
/// Null by default.
final ButtonStyle? style;
/// {@macro flutter.material.inkwell.statesController}
final MaterialStatesController? statesController;
/// {@macro flutter.material.Material.clipBehavior}
///
/// Defaults to [Clip.none].
final Clip clipBehavior;
/// An optional icon to display before the [child] label.
final Widget? leadingIcon;
/// An optional icon to display after the [child] label.
final Widget? trailingIcon;
/// The widget displayed in the center of this button.
///
/// Typically this is the button's label, using a [Text] widget.
///
/// {@macro flutter.widgets.ProxyWidget.child}
final Widget? child;
/// Whether the button is enabled or disabled.
///
/// To enable a button, set its [onPressed] property to a non-null value.
bool get enabled => onPressed != null;
@override
State<MenuItemButton> createState() => _MenuItemButtonState();
/// Defines the button's default appearance.
///
/// {@macro flutter.material.text_button.default_style_of}
///
/// {@macro flutter.material.text_button.material3_defaults}
ButtonStyle defaultStyleOf(BuildContext context) {
return _MenuButtonDefaultsM3(context);
}
/// Returns the [MenuButtonThemeData.style] of the closest
/// [MenuButtonTheme] ancestor.
ButtonStyle? themeStyleOf(BuildContext context) {
return MenuButtonTheme.of(context).style;
}
/// A static convenience method that constructs a [MenuItemButton]'s
/// [ButtonStyle] given simple values.
///
/// The [foregroundColor] color is used to create a [MaterialStateProperty]
/// [ButtonStyle.foregroundColor] value. Specify a value for [foregroundColor]
/// to specify the color of the button's icons. Use [backgroundColor] for the
/// button's background fill color. Use [disabledForegroundColor] and
/// [disabledBackgroundColor] to specify the button's disabled icon and fill
/// color.
///
/// All of the other parameters are either used directly or used to create a
/// [MaterialStateProperty] with a single value for all states.
///
/// All parameters default to null, by default this method returns a
/// [ButtonStyle] that doesn't override anything.
///
/// For example, to override the default foreground color for a
/// [MenuItemButton], as well as its overlay color, with all of the standard
/// opacity adjustments for the pressed, focused, and hovered states, one
/// could write:
///
/// ```dart
/// MenuItemButton(
/// leadingIcon: const Icon(Icons.pets),
/// style: MenuItemButton.styleFrom(foregroundColor: Colors.green),
/// onPressed: () {
/// // ...
/// },
/// child: const Text('Button Label'),
/// ),
/// ```
static ButtonStyle styleFrom({
Color? foregroundColor,
Color? backgroundColor,
Color? disabledForegroundColor,
Color? disabledBackgroundColor,
Color? shadowColor,
Color? surfaceTintColor,
Color? iconColor,
TextStyle? textStyle,
double? elevation,
EdgeInsetsGeometry? padding,
Size? minimumSize,
Size? fixedSize,
Size? maximumSize,
MouseCursor? enabledMouseCursor,
MouseCursor? disabledMouseCursor,
BorderSide? side,
OutlinedBorder? shape,
VisualDensity? visualDensity,
MaterialTapTargetSize? tapTargetSize,
Duration? animationDuration,
bool? enableFeedback,
AlignmentGeometry? alignment,
InteractiveInkFeatureFactory? splashFactory,
}) {
return TextButton.styleFrom(
foregroundColor: foregroundColor,
backgroundColor: backgroundColor,
disabledBackgroundColor: disabledBackgroundColor,
disabledForegroundColor: disabledForegroundColor,
shadowColor: shadowColor,
surfaceTintColor: surfaceTintColor,
iconColor: iconColor,
textStyle: textStyle,
elevation: elevation,
padding: padding,
minimumSize: minimumSize,
fixedSize: fixedSize,
maximumSize: maximumSize,
enabledMouseCursor: enabledMouseCursor,
disabledMouseCursor: disabledMouseCursor,
side: side,
shape: shape,
visualDensity: visualDensity,
tapTargetSize: tapTargetSize,
animationDuration: animationDuration,
enableFeedback: enableFeedback,
alignment: alignment,
splashFactory: splashFactory,
);
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(FlagProperty('enabled', value: onPressed != null, ifFalse: 'DISABLED'));
properties.add(DiagnosticsProperty<String>('child', child.toString()));
properties.add(DiagnosticsProperty<ButtonStyle?>('style', style, defaultValue: null));
properties.add(DiagnosticsProperty<MenuSerializableShortcut?>('shortcut', shortcut, defaultValue: null));
properties.add(DiagnosticsProperty<Widget?>('leadingIcon', leadingIcon, defaultValue: null));
properties.add(DiagnosticsProperty<Widget?>('trailingIcon', trailingIcon, defaultValue: null));
properties.add(DiagnosticsProperty<FocusNode?>('focusNode', focusNode, defaultValue: null));
properties.add(EnumProperty<Clip>('clipBehavior', clipBehavior, defaultValue: Clip.none));
properties.add(DiagnosticsProperty<MaterialStatesController?>('statesController', statesController, defaultValue: null));
}
}