This repository has been archived by the owner on Feb 22, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9.8k
/
actions.dart
1820 lines (1654 loc) · 67.3 KB
/
actions.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 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter/services.dart';
import 'basic.dart';
import 'focus_manager.dart';
import 'focus_scope.dart';
import 'framework.dart';
import 'media_query.dart';
import 'shortcuts.dart';
// BuildContext/Element doesn't have a parent accessor, but it can be
// simulated with visitAncestorElements. _getParent is needed because
// context.getElementForInheritedWidgetOfExactType will return itself if it
// happens to be of the correct type. getParent should be O(1), since we
// always return false at the first ancestor.
BuildContext _getParent(BuildContext context) {
late final BuildContext parent;
context.visitAncestorElements((Element ancestor) {
parent = ancestor;
return false;
});
return parent;
}
/// An abstract class representing a particular configuration of an [Action].
///
/// This class is what the [Shortcuts.shortcuts] map has as values, and is used
/// by an [ActionDispatcher] to look up an action and invoke it, giving it this
/// object to extract configuration information from.
///
/// See also:
///
/// * [Actions.invoke], which invokes the action associated with a specified
/// [Intent] using the [Actions] widget that most tightly encloses the given
/// [BuildContext].
@immutable
abstract class Intent with Diagnosticable {
/// Abstract const constructor. This constructor enables subclasses to provide
/// const constructors so that they can be used in const expressions.
const Intent();
/// An intent that is mapped to a [DoNothingAction], which, as the name
/// implies, does nothing.
///
/// This Intent is mapped to an action in the [WidgetsApp] that does nothing,
/// so that it can be bound to a key in a [Shortcuts] widget in order to
/// disable a key binding made above it in the hierarchy.
static const DoNothingIntent doNothing = DoNothingIntent._();
}
/// The kind of callback that an [Action] uses to notify of changes to the
/// action's state.
///
/// To register an action listener, call [Action.addActionListener].
typedef ActionListenerCallback = void Function(Action<Intent> action);
/// Base class for actions.
///
/// As the name implies, an [Action] is an action or command to be performed.
/// They are typically invoked as a result of a user action, such as a keyboard
/// shortcut in a [Shortcuts] widget, which is used to look up an [Intent],
/// which is given to an [ActionDispatcher] to map the [Intent] to an [Action]
/// and invoke it.
///
/// The [ActionDispatcher] can invoke an [Action] on the primary focus, or
/// without regard for focus.
///
/// ### Action Overriding
///
/// When using a leaf widget to build a more specialized widget, it's sometimes
/// desirable to change the default handling of an [Intent] defined in the leaf
/// widget. For instance, [TextField]'s [SelectAllTextIntent] by default selects
/// the text it currently contains, but in a US phone number widget that
/// consists of 3 different [TextField]s (area code, prefix and line number),
/// [SelectAllTextIntent] should instead select the text within all 3
/// [TextField]s.
///
/// An overridable [Action] is a special kind of [Action] created using the
/// [Action.overridable] constructor. It has access to a default [Action], and a
/// nullable override [Action]. It has the same behavior as its override if that
/// exists, and mirrors the behavior of its `defaultAction` otherwise.
///
/// The [Action.overridable] constructor creates overridable [Action]s that use
/// a [BuildContext] to find a suitable override in its ancestor [Actions]
/// widget. This can be used to provide a default implementation when creating a
/// general purpose leaf widget, and later override it when building a more
/// specialized widget using that leaf widget. Using the [TextField] example
/// above, the [TextField] widget uses an overridable [Action] to provide a
/// sensible default for [SelectAllTextIntent], while still allowing app
/// developers to change that if they add an ancestor [Actions] widget that maps
/// [SelectAllTextIntent] to a different [Action].
///
/// See the article on [Using Actions and
/// Shortcuts](https://docs.flutter.dev/development/ui/advanced/actions_and_shortcuts)
/// for a detailed explanation.
///
/// See also:
///
/// * [Shortcuts], which is a widget that contains a key map, in which it looks
/// up key combinations in order to invoke actions.
/// * [Actions], which is a widget that defines a map of [Intent] to [Action]
/// and allows redefining of actions for its descendants.
/// * [ActionDispatcher], a class that takes an [Action] and invokes it, passing
/// a given [Intent].
/// * [Action.overridable] for an example on how to make an [Action]
/// overridable.
abstract class Action<T extends Intent> with Diagnosticable {
/// Creates an [Action].
Action();
/// Creates an [Action] that allows itself to be overridden by the closest
/// ancestor [Action] in the given [context] that handles the same [Intent],
/// if one exists.
///
/// When invoked, the resulting [Action] tries to find the closest [Action] in
/// the given `context` that handles the same type of [Intent] as the
/// `defaultAction`, then calls its [Action.invoke] method. When no override
/// [Action]s can be found, it invokes the `defaultAction`.
///
/// An overridable action delegates everything to its override if one exists,
/// and has the same behavior as its `defaultAction` otherwise. For this
/// reason, the override has full control over whether and how an [Intent]
/// should be handled, or a key event should be consumed. An override
/// [Action]'s [callingAction] property will be set to the [Action] it
/// currently overrides, giving it access to the default behavior. See the
/// [callingAction] property for an example.
///
/// The `context` argument is the [BuildContext] to find the override with. It
/// is typically a [BuildContext] above the [Actions] widget that contains
/// this overridable [Action].
///
/// The `defaultAction` argument is the [Action] to be invoked where there's
/// no ancestor [Action]s can't be found in `context` that handle the same
/// type of [Intent].
///
/// This is useful for providing a set of default [Action]s in a leaf widget
/// to allow further overriding, or to allow the [Intent] to propagate to
/// parent widgets that also support this [Intent].
///
/// {@tool dartpad}
/// This sample shows how to implement a rudimentary `CopyableText` widget
/// that responds to Ctrl-C by copying its own content to the clipboard.
///
/// if `CopyableText` is to be provided in a package, developers using the
/// widget may want to change how copying is handled. As the author of the
/// package, you can enable that by making the corresponding [Action]
/// overridable. In the second part of the code sample, three `CopyableText`
/// widgets are used to build a verification code widget which overrides the
/// "copy" action by copying the combined numbers from all three `CopyableText`
/// widgets.
///
/// ** See code in examples/api/lib/widgets/actions/action.action_overridable.0.dart **
/// {@end-tool}
factory Action.overridable({
required Action<T> defaultAction,
required BuildContext context,
}) {
return defaultAction._makeOverridableAction(context);
}
final ObserverList<ActionListenerCallback> _listeners = ObserverList<ActionListenerCallback>();
Action<T>? _currentCallingAction;
// ignore: use_setters_to_change_properties, (code predates enabling of this lint)
void _updateCallingAction(Action<T>? value) {
_currentCallingAction = value;
}
/// The [Action] overridden by this [Action].
///
/// The [Action.overridable] constructor creates an overridable [Action] that
/// allows itself to be overridden by the closest ancestor [Action], and falls
/// back to its own `defaultAction` when no overrides can be found. When an
/// override is present, an overridable [Action] forwards all incoming
/// method calls to the override, and allows the override to access the
/// `defaultAction` via its [callingAction] property.
///
/// Before forwarding the call to the override, the overridable [Action] is
/// responsible for setting [callingAction] to its `defaultAction`, which is
/// already taken care of by the overridable [Action] created using
/// [Action.overridable].
///
/// This property is only non-null when this [Action] is an override of the
/// [callingAction], and is currently being invoked from [callingAction].
///
/// Invoking [callingAction]'s methods, or accessing its properties, is
/// allowed and does not introduce infinite loops or infinite recursions.
///
/// {@tool snippet}
/// An example `Action` that handles [PasteTextIntent] but has mostly the same
/// behavior as the overridable action. It's OK to call
/// `callingAction?.isActionEnabled` in the implementation of this `Action`.
///
/// ```dart
/// class MyPasteAction extends Action<PasteTextIntent> {
/// @override
/// Object? invoke(PasteTextIntent intent) {
/// print(intent);
/// return callingAction?.invoke(intent);
/// }
///
/// @override
/// bool get isActionEnabled => callingAction?.isActionEnabled ?? false;
///
/// @override
/// bool consumesKey(PasteTextIntent intent) => callingAction?.consumesKey(intent) ?? false;
/// }
/// ```
/// {@end-tool}
@protected
Action<T>? get callingAction => _currentCallingAction;
/// Gets the type of intent this action responds to.
Type get intentType => T;
/// Returns true if the action is enabled and is ready to be invoked.
///
/// This will be called by the [ActionDispatcher] before attempting to invoke
/// the action.
bool isEnabled(T intent) => isActionEnabled;
/// Whether this [Action] is inherently enabled.
///
/// If [isActionEnabled] is false, then this [Action] is disabled for any
/// given [Intent].
//
/// If the enabled state changes, overriding subclasses must call
/// [notifyActionListeners] to notify any listeners of the change.
///
/// In the case of an overridable `Action`, accessing this property creates
/// an dependency on the overridable `Action`s `lookupContext`.
bool get isActionEnabled => true;
/// Indicates whether this action should treat key events mapped to this
/// action as being "handled" when it is invoked via the key event.
///
/// If the key is handled, then no other key event handlers in the focus chain
/// will receive the event.
///
/// If the key event is not handled, it will be passed back to the engine, and
/// continue to be processed there, allowing text fields and non-Flutter
/// widgets to receive the key event.
///
/// The default implementation returns true.
bool consumesKey(T intent) => true;
/// Converts the result of [invoke] of this action to a [KeyEventResult].
///
/// This is typically used when the action is invoked in response to a keyboard
/// shortcut.
///
/// The [invokeResult] argument is the value returned by the [invoke] method.
///
/// By default, calls [consumesKey] and converts the returned boolean to
/// [KeyEventResult.handled] if it's true, and [KeyEventResult.skipRemainingHandlers]
/// if it's false.
///
/// Concrete implementations may refine the type of [invokeResult], since
/// they know the type returned by [invoke].
KeyEventResult toKeyEventResult(T intent, covariant Object? invokeResult) {
return consumesKey(intent)
? KeyEventResult.handled
: KeyEventResult.skipRemainingHandlers;
}
/// Called when the action is to be performed.
///
/// This is called by the [ActionDispatcher] when an action is invoked via
/// [Actions.invoke], or when an action is invoked using
/// [ActionDispatcher.invokeAction] directly.
///
/// This method is only meant to be invoked by an [ActionDispatcher], or by
/// its subclasses, and only when [isEnabled] is true.
///
/// When overriding this method, the returned value can be any Object, but
/// changing the return type of the override to match the type of the returned
/// value provides more type safety.
///
/// For instance, if an override of [invoke] returned an `int`, then it might
/// be defined like so:
///
/// ```dart
/// class IncrementIntent extends Intent {
/// const IncrementIntent({required this.index});
///
/// final int index;
/// }
///
/// class MyIncrementAction extends Action<IncrementIntent> {
/// @override
/// int invoke(IncrementIntent intent) {
/// return intent.index + 1;
/// }
/// }
/// ```
///
/// To receive the result of invoking an action, it must be invoked using
/// [Actions.invoke], or by invoking it using an [ActionDispatcher]. An action
/// invoked via a [Shortcuts] widget will have its return value ignored.
@protected
Object? invoke(T intent);
/// Register a callback to listen for changes to the state of this action.
///
/// If you call this, you must call [removeActionListener] a matching number
/// of times, or memory leaks will occur. To help manage this and avoid memory
/// leaks, use of the [ActionListener] widget to register and unregister your
/// listener appropriately is highly recommended.
///
/// {@template flutter.widgets.Action.addActionListener}
/// If a listener had been added twice, and is removed once during an
/// iteration (i.e. in response to a notification), it will still be called
/// again. If, on the other hand, it is removed as many times as it was
/// registered, then it will no longer be called. This odd behavior is the
/// result of the [Action] not being able to determine which listener
/// is being removed, since they are identical, and therefore conservatively
/// still calling all the listeners when it knows that any are still
/// registered.
///
/// This surprising behavior can be unexpectedly observed when registering a
/// listener on two separate objects which are both forwarding all
/// registrations to a common upstream object.
/// {@endtemplate}
@mustCallSuper
void addActionListener(ActionListenerCallback listener) => _listeners.add(listener);
/// Remove a previously registered closure from the list of closures that are
/// notified when the object changes.
///
/// If the given listener is not registered, the call is ignored.
///
/// If you call [addActionListener], you must call this method a matching
/// number of times, or memory leaks will occur. To help manage this and avoid
/// memory leaks, use of the [ActionListener] widget to register and
/// unregister your listener appropriately is highly recommended.
///
/// {@macro flutter.widgets.Action.addActionListener}
@mustCallSuper
void removeActionListener(ActionListenerCallback listener) => _listeners.remove(listener);
/// Call all the registered listeners.
///
/// Subclasses should call this method whenever the object changes, to notify
/// any clients the object may have changed. Listeners that are added during this
/// iteration will not be visited. Listeners that are removed during this
/// iteration will not be visited after they are removed.
///
/// Exceptions thrown by listeners will be caught and reported using
/// [FlutterError.reportError].
///
/// Surprising behavior can result when reentrantly removing a listener (i.e.
/// in response to a notification) that has been registered multiple times.
/// See the discussion at [removeActionListener].
@protected
@visibleForTesting
@pragma('vm:notify-debugger-on-exception')
void notifyActionListeners() {
if (_listeners.isEmpty) {
return;
}
// Make a local copy so that a listener can unregister while the list is
// being iterated over.
final List<ActionListenerCallback> localListeners = List<ActionListenerCallback>.of(_listeners);
for (final ActionListenerCallback listener in localListeners) {
InformationCollector? collector;
assert(() {
collector = () => <DiagnosticsNode>[
DiagnosticsProperty<Action<T>>(
'The $runtimeType sending notification was',
this,
style: DiagnosticsTreeStyle.errorProperty,
),
];
return true;
}());
try {
if (_listeners.contains(listener)) {
listener(this);
}
} catch (exception, stack) {
FlutterError.reportError(FlutterErrorDetails(
exception: exception,
stack: stack,
library: 'widgets library',
context: ErrorDescription('while dispatching notifications for $runtimeType'),
informationCollector: collector,
));
}
}
}
Action<T> _makeOverridableAction(BuildContext context) {
return _OverridableAction<T>(defaultAction: this, lookupContext: context);
}
}
/// A helper widget for making sure that listeners on an action are removed properly.
///
/// Listeners on the [Action] class must have their listener callbacks removed
/// with [Action.removeActionListener] when the listener is disposed of. This widget
/// helps with that, by providing a lifetime for the connection between the
/// [listener] and the [Action], and by handling the adding and removing of
/// the [listener] at the right points in the widget lifecycle.
///
/// If you listen to an [Action] widget in a widget hierarchy, you should use
/// this widget. If you are using an [Action] outside of a widget context, then
/// you must call removeListener yourself.
///
/// {@tool dartpad}
/// This example shows how ActionListener handles adding and removing of
/// the [listener] in the widget lifecycle.
///
/// ** See code in examples/api/lib/widgets/actions/action_listener.0.dart **
/// {@end-tool}
///
@immutable
class ActionListener extends StatefulWidget {
/// Create a const [ActionListener].
///
/// The [listener], [action], and [child] arguments must not be null.
const ActionListener({
super.key,
required this.listener,
required this.action,
required this.child,
}) : assert(listener != null),
assert(action != null),
assert(child != null);
/// The [ActionListenerCallback] callback to register with the [action].
///
/// Must not be null.
final ActionListenerCallback listener;
/// The [Action] that the callback will be registered with.
///
/// Must not be null.
final Action<Intent> action;
/// {@macro flutter.widgets.ProxyWidget.child}
final Widget child;
@override
State<ActionListener> createState() => _ActionListenerState();
}
class _ActionListenerState extends State<ActionListener> {
@override
void initState() {
super.initState();
widget.action.addActionListener(widget.listener);
}
@override
void didUpdateWidget(ActionListener oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.action == widget.action && oldWidget.listener == widget.listener) {
return;
}
oldWidget.action.removeActionListener(oldWidget.listener);
widget.action.addActionListener(widget.listener);
}
@override
void dispose() {
widget.action.removeActionListener(widget.listener);
super.dispose();
}
@override
Widget build(BuildContext context) => widget.child;
}
/// An abstract [Action] subclass that adds an optional [BuildContext] to the
/// [invoke] method to be able to provide context to actions.
///
/// [ActionDispatcher.invokeAction] checks to see if the action it is invoking
/// is a [ContextAction], and if it is, supplies it with a context.
abstract class ContextAction<T extends Intent> extends Action<T> {
/// Called when the action is to be performed.
///
/// This is called by the [ActionDispatcher] when an action is invoked via
/// [Actions.invoke], or when an action is invoked using
/// [ActionDispatcher.invokeAction] directly.
///
/// This method is only meant to be invoked by an [ActionDispatcher], or by
/// its subclasses, and only when [isEnabled] is true.
///
/// The optional `context` parameter is the context of the invocation of the
/// action, and in the case of an action invoked by a [ShortcutManager], via
/// a [Shortcuts] widget, will be the context of the [Shortcuts] widget.
///
/// When overriding this method, the returned value can be any Object, but
/// changing the return type of the override to match the type of the returned
/// value provides more type safety.
///
/// For instance, if an override of [invoke] returned an `int`, then it might
/// be defined like so:
///
/// ```dart
/// class IncrementIntent extends Intent {
/// const IncrementIntent({required this.index});
///
/// final int index;
/// }
///
/// class MyIncrementAction extends ContextAction<IncrementIntent> {
/// @override
/// int invoke(IncrementIntent intent, [BuildContext? context]) {
/// return intent.index + 1;
/// }
/// }
/// ```
@protected
@override
Object? invoke(T intent, [BuildContext? context]);
@override
ContextAction<T> _makeOverridableAction(BuildContext context) {
return _OverridableContextAction<T>(defaultAction: this, lookupContext: context);
}
}
/// The signature of a callback accepted by [CallbackAction].
typedef OnInvokeCallback<T extends Intent> = Object? Function(T intent);
/// An [Action] that takes a callback in order to configure it without having to
/// create an explicit [Action] subclass just to call a callback.
///
/// See also:
///
/// * [Shortcuts], which is a widget that contains a key map, in which it looks
/// up key combinations in order to invoke actions.
/// * [Actions], which is a widget that defines a map of [Intent] to [Action]
/// and allows redefining of actions for its descendants.
/// * [ActionDispatcher], a class that takes an [Action] and invokes it using a
/// [FocusNode] for context.
class CallbackAction<T extends Intent> extends Action<T> {
/// A constructor for a [CallbackAction].
///
/// The `intentKey` and [onInvoke] parameters must not be null.
/// The [onInvoke] parameter is required.
CallbackAction({required this.onInvoke}) : assert(onInvoke != null);
/// The callback to be called when invoked.
///
/// Must not be null.
@protected
final OnInvokeCallback<T> onInvoke;
@override
Object? invoke(T intent) => onInvoke(intent);
}
/// An action dispatcher that invokes the actions given to it.
///
/// The [invokeAction] method on this class directly calls the [Action.invoke]
/// method on the [Action] object.
///
/// For [ContextAction] actions, if no `context` is provided, the
/// [BuildContext] of the [primaryFocus] is used instead.
///
/// See also:
///
/// - [ShortcutManager], that uses this class to invoke actions.
/// - [Shortcuts] widget, which defines key mappings to [Intent]s.
/// - [Actions] widget, which defines a mapping between a in [Intent] type and
/// an [Action].
class ActionDispatcher with Diagnosticable {
/// Creates an action dispatcher that invokes actions directly.
const ActionDispatcher();
/// Invokes the given `action`, passing it the given `intent`.
///
/// The action will be invoked with the given `context`, if given, but only if
/// the action is a [ContextAction] subclass. If no `context` is given, and
/// the action is a [ContextAction], then the context from the [primaryFocus]
/// is used.
///
/// Returns the object returned from [Action.invoke].
///
/// The caller must receive a `true` result from [Action.isEnabled] before
/// calling this function. This function will assert if the action is not
/// enabled when called.
Object? invokeAction(
covariant Action<Intent> action,
covariant Intent intent, [
BuildContext? context,
]) {
assert(action != null);
assert(intent != null);
assert(action.isEnabled(intent), 'Action must be enabled when calling invokeAction');
if (action is ContextAction) {
context ??= primaryFocus?.context;
return action.invoke(intent, context);
} else {
return action.invoke(intent);
}
}
}
/// A widget that establishes an [ActionDispatcher] and a map of [Intent] to
/// [Action] to be used by its descendants when invoking an [Action].
///
/// {@youtube 560 315 https://www.youtube.com/watch?v=XawP1i314WM}
///
/// Actions are typically invoked using [Actions.invoke] with the context
/// containing the ambient [Actions] widget.
///
/// {@tool dartpad}
/// This example creates a custom [Action] subclass `ModifyAction` for modifying
/// a model, and another, `SaveAction` for saving it.
///
/// This example demonstrates passing arguments to the [Intent] to be carried to
/// the [Action]. Actions can get data either from their own construction (like
/// the `model` in this example), or from the intent passed to them when invoked
/// (like the increment `amount` in this example).
///
/// This example also demonstrates how to use Intents to limit a widget's
/// dependencies on its surroundings. The `SaveButton` widget defined in this
/// example can invoke actions defined in its ancestor widgets, which can be
/// customized to match the part of the widget tree that it is in. It doesn't
/// need to know about the `SaveAction` class, only the `SaveIntent`, and it
/// only needs to know about a value notifier, not the entire model.
///
/// ** See code in examples/api/lib/widgets/actions/actions.0.dart **
/// {@end-tool}
///
/// See also:
///
/// * [ActionDispatcher], the object that this widget uses to manage actions.
/// * [Action], a class for containing and defining an invocation of a user
/// action.
/// * [Intent], a class that holds a unique [LocalKey] identifying an action,
/// as well as configuration information for running the [Action].
/// * [Shortcuts], a widget used to bind key combinations to [Intent]s.
class Actions extends StatefulWidget {
/// Creates an [Actions] widget.
///
/// The [child], [actions], and [dispatcher] arguments must not be null.
const Actions({
super.key,
this.dispatcher,
required this.actions,
required this.child,
}) : assert(actions != null),
assert(child != null);
/// The [ActionDispatcher] object that invokes actions.
///
/// This is what is returned from [Actions.of], and used by [Actions.invoke].
///
/// If this [dispatcher] is null, then [Actions.of] and [Actions.invoke] will
/// look up the tree until they find an Actions widget that has a dispatcher
/// set. If not such widget is found, then they will return/use a
/// default-constructed [ActionDispatcher].
final ActionDispatcher? dispatcher;
/// {@template flutter.widgets.actions.actions}
/// A map of [Intent] keys to [Action<Intent>] objects that defines which
/// actions this widget knows about.
///
/// For performance reasons, it is recommended that a pre-built map is
/// passed in here (e.g. a final variable from your widget class) instead of
/// defining it inline in the build function.
/// {@endtemplate}
final Map<Type, Action<Intent>> actions;
/// {@macro flutter.widgets.ProxyWidget.child}
final Widget child;
// Visits the Actions widget ancestors of the given element using
// getElementForInheritedWidgetOfExactType. Returns true if the visitor found
// what it was looking for.
static bool _visitActionsAncestors(BuildContext context, bool Function(InheritedElement element) visitor) {
InheritedElement? actionsElement = context.getElementForInheritedWidgetOfExactType<_ActionsMarker>();
while (actionsElement != null) {
if (visitor(actionsElement) == true) {
break;
}
// _getParent is needed here because
// context.getElementForInheritedWidgetOfExactType will return itself if it
// happens to be of the correct type.
final BuildContext parent = _getParent(actionsElement);
actionsElement = parent.getElementForInheritedWidgetOfExactType<_ActionsMarker>();
}
return actionsElement != null;
}
// Finds the nearest valid ActionDispatcher, or creates a new one if it
// doesn't find one.
static ActionDispatcher _findDispatcher(BuildContext context) {
ActionDispatcher? dispatcher;
_visitActionsAncestors(context, (InheritedElement element) {
final ActionDispatcher? found = (element.widget as _ActionsMarker).dispatcher;
if (found != null) {
dispatcher = found;
return true;
}
return false;
});
return dispatcher ?? const ActionDispatcher();
}
/// Returns a [VoidCallback] handler that invokes the bound action for the
/// given `intent` if the action is enabled, and returns null if the action is
/// not enabled, or no matching action is found.
///
/// This is intended to be used in widgets which have something similar to an
/// `onTap` handler, which takes a `VoidCallback`, and can be set to the
/// result of calling this function.
///
/// Creates a dependency on the [Actions] widget that maps the bound action so
/// that if the actions change, the context will be rebuilt and find the
/// updated action.
static VoidCallback? handler<T extends Intent>(BuildContext context, T intent) {
final Action<T>? action = Actions.maybeFind<T>(context);
if (action != null && action.isEnabled(intent)) {
return () {
// Could be that the action was enabled when the closure was created,
// but is now no longer enabled, so check again.
if (action.isEnabled(intent)) {
Actions.of(context).invokeAction(action, intent, context);
}
};
}
return null;
}
/// Finds the [Action] bound to the given intent type `T` in the given `context`.
///
/// Creates a dependency on the [Actions] widget that maps the bound action so
/// that if the actions change, the context will be rebuilt and find the
/// updated action.
///
/// The optional `intent` argument supplies the type of the intent to look for
/// if the concrete type of the intent sought isn't available. If not
/// supplied, then `T` is used.
///
/// If no [Actions] widget surrounds the given context, this function will
/// assert in debug mode, and throw an exception in release mode.
///
/// See also:
///
/// * [maybeFind], which is similar to this function, but will return null if
/// no [Actions] ancestor is found.
static Action<T> find<T extends Intent>(BuildContext context, { T? intent }) {
final Action<T>? action = maybeFind(context, intent: intent);
assert(() {
if (action == null) {
final Type type = intent?.runtimeType ?? T;
throw FlutterError(
'Unable to find an action for a $type in an $Actions widget '
'in the given context.\n'
"$Actions.find() was called on a context that doesn't contain an "
'$Actions widget with a mapping for the given intent type.\n'
'The context used was:\n'
' $context\n'
'The intent type requested was:\n'
' $type',
);
}
return true;
}());
return action!;
}
/// Finds the [Action] bound to the given intent type `T` in the given `context`.
///
/// Creates a dependency on the [Actions] widget that maps the bound action so
/// that if the actions change, the context will be rebuilt and find the
/// updated action.
///
/// The optional `intent` argument supplies the type of the intent to look for
/// if the concrete type of the intent sought isn't available. If not
/// supplied, then `T` is used.
///
/// If no [Actions] widget surrounds the given context, this function will
/// return null.
///
/// See also:
///
/// * [find], which is similar to this function, but will throw if
/// no [Actions] ancestor is found.
static Action<T>? maybeFind<T extends Intent>(BuildContext context, { T? intent }) {
Action<T>? action;
// Specialize the type if a runtime example instance of the intent is given.
// This allows this function to be called by code that doesn't know the
// concrete type of the intent at compile time.
final Type type = intent?.runtimeType ?? T;
assert(
type != Intent,
'The type passed to "find" resolved to "Intent": either a non-Intent '
'generic type argument or an example intent derived from Intent must be '
'specified. Intent may be used as the generic type as long as the optional '
'"intent" argument is passed.',
);
_visitActionsAncestors(context, (InheritedElement element) {
final _ActionsMarker actions = element.widget as _ActionsMarker;
final Action<T>? result = _castAction(actions, intent: intent);
if (result != null) {
context.dependOnInheritedElement(element);
action = result;
return true;
}
return false;
});
return action;
}
static Action<T>? _maybeFindWithoutDependingOn<T extends Intent>(BuildContext context, { T? intent }) {
Action<T>? action;
// Specialize the type if a runtime example instance of the intent is given.
// This allows this function to be called by code that doesn't know the
// concrete type of the intent at compile time.
final Type type = intent?.runtimeType ?? T;
assert(
type != Intent,
'The type passed to "find" resolved to "Intent": either a non-Intent '
'generic type argument or an example intent derived from Intent must be '
'specified. Intent may be used as the generic type as long as the optional '
'"intent" argument is passed.',
);
_visitActionsAncestors(context, (InheritedElement element) {
final _ActionsMarker actions = element.widget as _ActionsMarker;
final Action<T>? result = _castAction(actions, intent: intent);
if (result != null) {
action = result;
return true;
}
return false;
});
return action;
}
// Find the [Action] that handles the given `intent` in the given
// `_ActionsMarker`, and verify it has the right type parameter.
static Action<T>? _castAction<T extends Intent>(_ActionsMarker actionsMarker, { T? intent }) {
final Action<Intent>? mappedAction = actionsMarker.actions[intent?.runtimeType ?? T];
if (mappedAction is Action<T>?) {
return mappedAction;
} else {
assert(
false,
'$T cannot be handled by an Action of runtime type ${mappedAction.runtimeType}.'
);
return null;
}
}
/// Returns the [ActionDispatcher] associated with the [Actions] widget that
/// most tightly encloses the given [BuildContext].
///
/// Will return a newly created [ActionDispatcher] if no ambient [Actions]
/// widget is found.
static ActionDispatcher of(BuildContext context) {
assert(context != null);
final _ActionsMarker? marker = context.dependOnInheritedWidgetOfExactType<_ActionsMarker>();
return marker?.dispatcher ?? _findDispatcher(context);
}
/// Invokes the action associated with the given [Intent] using the
/// [Actions] widget that most tightly encloses the given [BuildContext].
///
/// This method returns the result of invoking the action's [Action.invoke]
/// method.
///
/// The `context` and `intent` arguments must not be null.
///
/// If the given `intent` doesn't map to an action, then it will look to the
/// next ancestor [Actions] widget in the hierarchy until it reaches the root.
///
/// This method will throw an exception if no ambient [Actions] widget is
/// found, or when a suitable [Action] is found but it returns false for
/// [Action.isEnabled].
static Object? invoke<T extends Intent>(
BuildContext context,
T intent,
) {
assert(intent != null);
assert(context != null);
Object? returnValue;
final bool actionFound = _visitActionsAncestors(context, (InheritedElement element) {
final _ActionsMarker actions = element.widget as _ActionsMarker;
final Action<T>? result = _castAction(actions, intent: intent);
if (result != null && result.isEnabled(intent)) {
// Invoke the action we found using the relevant dispatcher from the Actions
// Element we found.
returnValue = _findDispatcher(element).invokeAction(result, intent, context);
}
return result != null;
});
assert(() {
if (!actionFound) {
throw FlutterError(
'Unable to find an action for an Intent with type '
'${intent.runtimeType} in an $Actions widget in the given context.\n'
'$Actions.invoke() was unable to find an $Actions widget that '
"contained a mapping for the given intent, or the intent type isn't the "
'same as the type argument to invoke (which is $T - try supplying a '
'type argument to invoke if one was not given)\n'
'The context used was:\n'
' $context\n'
'The intent type requested was:\n'
' ${intent.runtimeType}',
);
}
return true;
}());
return returnValue;
}
/// Invokes the action associated with the given [Intent] using the
/// [Actions] widget that most tightly encloses the given [BuildContext].
///
/// This method returns the result of invoking the action's [Action.invoke]
/// method. If no action mapping was found for the specified intent, or if the
/// first action found was disabled, or the action itself returns null
/// from [Action.invoke], then this method returns null.
///
/// The `context` and `intent` arguments must not be null.
///
/// If the given `intent` doesn't map to an action, then it will look to the
/// next ancestor [Actions] widget in the hierarchy until it reaches the root.
/// If a suitable [Action] is found but its [Action.isEnabled] returns false,
/// the search will stop and this method will return null.
static Object? maybeInvoke<T extends Intent>(
BuildContext context,
T intent,
) {
assert(intent != null);
assert(context != null);
Object? returnValue;
_visitActionsAncestors(context, (InheritedElement element) {
final _ActionsMarker actions = element.widget as _ActionsMarker;
final Action<T>? result = _castAction(actions, intent: intent);
if (result != null && result.isEnabled(intent)) {
// Invoke the action we found using the relevant dispatcher from the Actions
// Element we found.
returnValue = _findDispatcher(element).invokeAction(result, intent, context);
}
return result != null;
});
return returnValue;
}
@override
State<Actions> createState() => _ActionsState();
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DiagnosticsProperty<ActionDispatcher>('dispatcher', dispatcher));
properties.add(DiagnosticsProperty<Map<Type, Action<Intent>>>('actions', actions));
}
}
class _ActionsState extends State<Actions> {
// The set of actions that this Actions widget is current listening to.
Set<Action<Intent>>? listenedActions = <Action<Intent>>{};
// Used to tell the marker to rebuild its dependencies when the state of an
// action in the map changes.
Object rebuildKey = Object();
@override
void initState() {
super.initState();
_updateActionListeners();
}
void _handleActionChanged(Action<Intent> action) {
// Generate a new key so that the marker notifies dependents.
setState(() {
rebuildKey = Object();
});
}
void _updateActionListeners() {
final Set<Action<Intent>> widgetActions = widget.actions.values.toSet();
final Set<Action<Intent>> removedActions = listenedActions!.difference(widgetActions);
final Set<Action<Intent>> addedActions = widgetActions.difference(listenedActions!);