forked from flutter/flutter
/
focus_manager.dart
2197 lines (2042 loc) · 89.4 KB
/
focus_manager.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:async';
import 'dart:ui';
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/painting.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter/services.dart';
import 'binding.dart';
import 'focus_scope.dart';
import 'focus_traversal.dart';
import 'framework.dart';
/// Setting to true will cause extensive logging to occur when focus changes occur.
///
/// Can be used to debug focus issues: each time the focus changes, the focus
/// tree will be printed and requests for focus and other focus operations will
/// be logged.
bool debugFocusChanges = false;
// When using _focusDebug, always call it like so:
//
// assert(_focusDebug(() => 'Blah $foo'));
//
// It needs to be inside the assert in order to be removed in release mode, and
// it needs to use a closure to generate the string in order to avoid string
// interpolation when debugFocusChanges is false.
//
// It will throw a StateError if you try to call it when the app is in release
// mode.
bool _focusDebug(
String Function() messageFunc, [
Iterable<Object> Function()? detailsFunc,
]) {
if (kReleaseMode) {
throw StateError(
'_focusDebug was called in Release mode. It should always be wrapped in '
'an assert. Always call _focusDebug like so:\n'
r" assert(_focusDebug(() => 'Blah $foo'));"
);
}
if (!debugFocusChanges) {
return true;
}
debugPrint('FOCUS: ${messageFunc()}');
final Iterable<Object> details = detailsFunc?.call() ?? const <Object>[];
if (details.isNotEmpty) {
for (final Object detail in details) {
debugPrint(' $detail');
}
}
// Return true so that it can be used inside of an assert.
return true;
}
/// An enum that describes how to handle a key event handled by a
/// [FocusOnKeyCallback] or [FocusOnKeyEventCallback].
enum KeyEventResult {
/// The key event has been handled, and the event should not be propagated to
/// other key event handlers.
handled,
/// The key event has not been handled, and the event should continue to be
/// propagated to other key event handlers, even non-Flutter ones.
ignored,
/// The key event has not been handled, but the key event should not be
/// propagated to other key event handlers.
///
/// It will be returned to the platform embedding to be propagated to text
/// fields and non-Flutter key event handlers on the platform.
skipRemainingHandlers,
}
/// Combine the results returned by multiple [FocusOnKeyCallback]s or
/// [FocusOnKeyEventCallback]s.
///
/// If any callback returns [KeyEventResult.handled], the node considers the
/// message handled; otherwise, if any callback returns
/// [KeyEventResult.skipRemainingHandlers], the node skips the remaining
/// handlers without preventing the platform to handle; otherwise the node is
/// ignored.
KeyEventResult combineKeyEventResults(Iterable<KeyEventResult> results) {
bool hasSkipRemainingHandlers = false;
for (final KeyEventResult result in results) {
switch (result) {
case KeyEventResult.handled:
return KeyEventResult.handled;
case KeyEventResult.skipRemainingHandlers:
hasSkipRemainingHandlers = true;
case KeyEventResult.ignored:
break;
}
}
return hasSkipRemainingHandlers ?
KeyEventResult.skipRemainingHandlers :
KeyEventResult.ignored;
}
/// Signature of a callback used by [Focus.onKey] and [FocusScope.onKey]
/// to receive key events.
///
/// This kind of callback is deprecated and will be removed at a future date.
/// Use [FocusOnKeyEventCallback] and associated APIs instead.
///
/// The [node] is the node that received the event.
///
/// Returns a [KeyEventResult] that describes how, and whether, the key event
/// was handled.
@Deprecated(
'Use FocusOnKeyEventCallback instead. '
'This feature was deprecated after v3.18.0-2.0.pre.',
)
typedef FocusOnKeyCallback = KeyEventResult Function(FocusNode node, RawKeyEvent event);
/// Signature of a callback used by [Focus.onKeyEvent] and [FocusScope.onKeyEvent]
/// to receive key events.
///
/// The [node] is the node that received the event.
///
/// Returns a [KeyEventResult] that describes how, and whether, the key event
/// was handled.
typedef FocusOnKeyEventCallback = KeyEventResult Function(FocusNode node, KeyEvent event);
/// Signature of a callback used by [FocusManager.addEarlyKeyEventHandler] and
/// [FocusManager.addLateKeyEventHandler].
///
/// The `event` parameter is a [KeyEvent] that is being sent to the callback to
/// be handled.
///
/// The [KeyEventResult] return value indicates whether or not the event will
/// continue to be propagated. If the value returned is [KeyEventResult.handled]
/// or [KeyEventResult.skipRemainingHandlers], then the event will not continue
/// to be propagated.
typedef OnKeyEventCallback = KeyEventResult Function(KeyEvent event);
// Represents a pending autofocus request.
@immutable
class _Autofocus {
const _Autofocus({ required this.scope, required this.autofocusNode });
final FocusScopeNode scope;
final FocusNode autofocusNode;
// Applies the autofocus request, if the node is still attached to the
// original scope and the scope has no focused child.
//
// The widget tree is responsible for calling reparent/detach on attached
// nodes to keep their parent/manager information up-to-date, so here we can
// safely check if the scope/node involved in each autofocus request is
// still attached, and discard the ones which are no longer attached to the
// original manager.
void applyIfValid(FocusManager manager) {
final bool shouldApply = (scope.parent != null || identical(scope, manager.rootScope))
&& identical(scope._manager, manager)
&& scope.focusedChild == null
&& autofocusNode.ancestors.contains(scope);
if (shouldApply) {
assert(_focusDebug(() => 'Applying autofocus: $autofocusNode'));
autofocusNode._doRequestFocus(findFirstFocus: true);
} else {
assert(_focusDebug(() => 'Autofocus request discarded for node: $autofocusNode.'));
}
}
}
/// An attachment point for a [FocusNode].
///
/// Using a [FocusAttachment] is rarely needed, unless building something
/// akin to the [Focus] or [FocusScope] widgets from scratch.
///
/// Once created, a [FocusNode] must be attached to the widget tree by its
/// _host_ [StatefulWidget] via a [FocusAttachment] object. [FocusAttachment]s
/// are owned by the [StatefulWidget] that hosts a [FocusNode] or
/// [FocusScopeNode]. There can be multiple [FocusAttachment]s for each
/// [FocusNode], but the node will only ever be attached to one of them at a
/// time.
///
/// This attachment is created by calling [FocusNode.attach], usually from the
/// host widget's [State.initState] method. If the widget is updated to have a
/// different focus node, then the new node needs to be attached in
/// [State.didUpdateWidget], after calling [detach] on the previous
/// [FocusAttachment]. Once detached, the attachment is defunct and will no
/// longer make changes to the [FocusNode] through [reparent].
///
/// Without these attachment points, it would be possible for a focus node to
/// simultaneously be attached to more than one part of the widget tree during
/// the build stage.
class FocusAttachment {
/// A private constructor, because [FocusAttachment]s are only to be created
/// by [FocusNode.attach].
FocusAttachment._(this._node);
// The focus node that this attachment manages an attachment for. The node may
// not yet have a parent, or may have been detached from this attachment, so
// don't count on this node being in a usable state.
final FocusNode _node;
/// Returns true if the associated node is attached to this attachment.
///
/// It is possible to be attached to the widget tree, but not be placed in
/// the focus tree (i.e. to not have a parent yet in the focus tree).
bool get isAttached => _node._attachment == this;
/// Detaches the [FocusNode] this attachment point is associated with from the
/// focus tree, and disconnects it from this attachment point.
///
/// Calling [FocusNode.dispose] will also automatically detach the node.
void detach() {
assert(_focusDebug(() => 'Detaching node:', () => <Object>[_node, 'With enclosing scope ${_node.enclosingScope}']));
if (isAttached) {
if (_node.hasPrimaryFocus || (_node._manager != null && _node._manager!._markedForFocus == _node)) {
_node.unfocus(disposition: UnfocusDisposition.previouslyFocusedChild);
}
// This node is no longer in the tree, so shouldn't send notifications anymore.
_node._manager?._markDetached(_node);
_node._parent?._removeChild(_node);
_node._attachment = null;
assert(!_node.hasPrimaryFocus);
assert(_node._manager?._markedForFocus != _node);
}
assert(!isAttached);
}
/// Ensures that the [FocusNode] attached at this attachment point has the
/// proper parent node, changing it if necessary.
///
/// If given, ensures that the given [parent] node is the parent of the node
/// that is attached at this attachment point, changing it if necessary.
/// However, it is usually not necessary to supply an explicit parent, since
/// [reparent] will use [Focus.of] to determine the correct parent node for
/// the context given in [FocusNode.attach].
///
/// If [isAttached] is false, then calling this method does nothing.
///
/// Should be called whenever the associated widget is rebuilt in order to
/// maintain the focus hierarchy.
///
/// A [StatefulWidget] that hosts a [FocusNode] should call this method on the
/// node it hosts during its [State.build] or [State.didChangeDependencies]
/// methods in case the widget is moved from one location in the tree to
/// another location that has a different [FocusScope] or context.
///
/// The optional [parent] argument must be supplied when not using [Focus] and
/// [FocusScope] widgets to build the focus tree, or if there is a need to
/// supply the parent explicitly (which are both uncommon).
void reparent({FocusNode? parent}) {
if (isAttached) {
assert(_node.context != null);
parent ??= Focus.maybeOf(_node.context!, scopeOk: true);
parent ??= _node.context!.owner!.focusManager.rootScope;
parent._reparent(_node);
}
}
}
/// Describe what should happen after [FocusNode.unfocus] is called.
///
/// See also:
///
/// * [FocusNode.unfocus], which takes this as its `disposition` parameter.
enum UnfocusDisposition {
/// Focus the nearest focusable enclosing scope of this node, but do not
/// descend to locate the leaf [FocusScopeNode.focusedChild] the way
/// [previouslyFocusedChild] does.
///
/// Focusing the scope in this way clears the [FocusScopeNode.focusedChild]
/// history for the enclosing scope when it receives focus. Because of this,
/// calling a traversal method like [FocusNode.nextFocus] after unfocusing
/// will cause the [FocusTraversalPolicy] to pick the node it thinks should be
/// first in the scope.
///
/// This is the default disposition for [FocusNode.unfocus].
scope,
/// Focus the previously focused child of the nearest focusable enclosing
/// scope of this node.
///
/// If there is no previously focused child, then this is equivalent to
/// using the [scope] disposition.
///
/// Unfocusing with this disposition will cause [FocusNode.unfocus] to walk up
/// the tree to the nearest focusable enclosing scope, then start to walk down
/// the tree, looking for a focused child at its
/// [FocusScopeNode.focusedChild].
///
/// If the [FocusScopeNode.focusedChild] is a scope, then look for its
/// [FocusScopeNode.focusedChild], and so on, finding the leaf
/// [FocusScopeNode.focusedChild] that is not a scope, or, failing that, a
/// leaf scope that has no focused child.
previouslyFocusedChild,
}
/// An object that can be used by a stateful widget to obtain the keyboard focus
/// and to handle keyboard events.
///
/// _Please see the [Focus] and [FocusScope] widgets, which are utility widgets
/// that manage their own [FocusNode]s and [FocusScopeNode]s, respectively. If
/// they aren't appropriate, [FocusNode]s can be managed directly, but doing this
/// is rare._
///
/// [FocusNode]s are persistent objects that form a _focus tree_ that is a
/// representation of the widgets in the hierarchy that are interested in focus.
/// A focus node might need to be created if it is passed in from an ancestor of
/// a [Focus] widget to control the focus of the children from the ancestor, or
/// a widget might need to host one if the widget subsystem is not being used,
/// or if the [Focus] and [FocusScope] widgets provide insufficient control.
///
/// [FocusNode]s are organized into _scopes_ (see [FocusScopeNode]), which form
/// sub-trees of nodes that restrict traversal to a group of nodes. Within a
/// scope, the most recent nodes to have focus are remembered, and if a node is
/// focused and then unfocused, the previous node receives focus again.
///
/// The focus node hierarchy can be traversed using the [parent], [children],
/// [ancestors] and [descendants] accessors.
///
/// [FocusNode]s are [ChangeNotifier]s, so a listener can be registered to
/// receive a notification when the focus changes. Listeners will also be
/// notified when [skipTraversal], [canRequestFocus], [descendantsAreFocusable],
/// and [descendantsAreTraversable] properties are updated. If the [Focus] and
/// [FocusScope] widgets are being used to manage the nodes, consider
/// establishing an [InheritedWidget] dependency on them by calling [Focus.of]
/// or [FocusScope.of] instead. [FocusNode.hasFocus] can also be used to
/// establish a similar dependency, especially if all that is needed is to
/// determine whether or not the widget is focused at build time.
///
/// To see the focus tree in the debug console, call [debugDumpFocusTree]. To
/// get the focus tree as a string, call [debugDescribeFocusTree].
///
/// {@template flutter.widgets.FocusNode.lifecycle}
/// ## Lifecycle
///
/// There are several actors involved in the lifecycle of a
/// [FocusNode]/[FocusScopeNode]. They are created and disposed by their
/// _owner_, attached, detached, and re-parented using a [FocusAttachment] by
/// their _host_ (which must be owned by the [State] of a [StatefulWidget]), and
/// they are managed by the [FocusManager]. Different parts of the [FocusNode]
/// API are intended for these different actors.
///
/// [FocusNode]s (and hence [FocusScopeNode]s) are persistent objects that form
/// part of a _focus tree_ that is a sparse representation of the widgets in the
/// hierarchy that are interested in receiving keyboard events. They must be
/// managed like other persistent state, which is typically done by a
/// [StatefulWidget] that owns the node. A stateful widget that owns a focus
/// scope node must call [dispose] from its [State.dispose] method.
///
/// Once created, a [FocusNode] must be attached to the widget tree via a
/// [FocusAttachment] object. This attachment is created by calling [attach],
/// usually from the [State.initState] method. If the hosting widget is updated
/// to have a different focus node, then the updated node needs to be attached
/// in [State.didUpdateWidget], after calling [FocusAttachment.detach] on the
/// previous [FocusAttachment].
///
/// Because [FocusNode]s form a sparse representation of the widget tree, they
/// must be updated whenever the widget tree is rebuilt. This is done by calling
/// [FocusAttachment.reparent], usually from the [State.build] or
/// [State.didChangeDependencies] methods of the widget that represents the
/// focused region, so that the [BuildContext] assigned to the [FocusScopeNode]
/// can be tracked (the context is used to obtain the [RenderObject], from which
/// the geometry of focused regions can be determined).
///
/// Creating a [FocusNode] each time [State.build] is invoked will cause the
/// focus to be lost each time the widget is built, which is usually not desired
/// behavior (call [unfocus] if losing focus is desired).
///
/// If, as is common, the hosting [StatefulWidget] is also the owner of the
/// focus node, then it will also call [dispose] from its [State.dispose] (in
/// which case the [FocusAttachment.detach] may be skipped, since dispose will
/// automatically detach). If another object owns the focus node, then it must
/// call [dispose] when the node is done being used.
/// {@endtemplate}
///
/// {@template flutter.widgets.FocusNode.keyEvents}
/// ## Key Event Propagation
///
/// The [FocusManager] receives key events from [HardwareKeyboard] and will pass
/// them to the focused nodes. It starts with the node with the primary focus,
/// and will call the [onKeyEvent] callback for that node. If the callback
/// returns [KeyEventResult.ignored], indicating that it did not handle the
/// event, the [FocusManager] will move to the parent of that node and call its
/// [onKeyEvent]. If that [onKeyEvent] returns [KeyEventResult.handled], then it
/// will stop propagating the event. If it reaches the root [FocusScopeNode],
/// [FocusManager.rootScope], the event is discarded.
/// {@endtemplate}
///
/// ## Focus Traversal
///
/// The term _traversal_, sometimes called _tab traversal_, refers to moving the
/// focus from one widget to the next in a particular order (also sometimes
/// referred to as the _tab order_, since the TAB key is often bound to the
/// action to move to the next widget).
///
/// To give focus to the logical _next_ or _previous_ widget in the UI, call the
/// [nextFocus] or [previousFocus] methods. To give the focus to a widget in a
/// particular direction, call the [focusInDirection] method.
///
/// The policy for what the _next_ or _previous_ widget is, or the widget in a
/// particular direction, is determined by the [FocusTraversalPolicy] in force.
///
/// The ambient policy is determined by looking up the widget hierarchy for a
/// [FocusTraversalGroup] widget, and obtaining the focus traversal policy from
/// it. Different focus nodes can inherit difference policies, so part of the
/// app can go in a predefined order (using [OrderedTraversalPolicy]), and part
/// can go in reading order (using [ReadingOrderTraversalPolicy]), depending
/// upon the use case.
///
/// Predefined policies include [WidgetOrderTraversalPolicy],
/// [ReadingOrderTraversalPolicy], [OrderedTraversalPolicy], and
/// [DirectionalFocusTraversalPolicyMixin], but custom policies can be built
/// based upon these policies. See [FocusTraversalPolicy] for more information.
///
/// {@tool dartpad}
/// This example shows how a FocusNode should be managed if not using the
/// [Focus] or [FocusScope] widgets. See the [Focus] widget for a similar
/// example using [Focus] and [FocusScope] widgets.
///
/// ** See code in examples/api/lib/widgets/focus_manager/focus_node.0.dart **
/// {@end-tool}
///
/// See also:
///
/// * [Focus], a widget that manages a [FocusNode] and provides access to focus
/// information and actions to its descendant widgets.
/// * [FocusTraversalGroup], a widget used to group together and configure the
/// focus traversal policy for a widget subtree.
/// * [FocusManager], a singleton that manages the primary focus and distributes
/// key events to focused nodes.
/// * [FocusTraversalPolicy], a class used to determine how to move the focus to
/// other nodes.
class FocusNode with DiagnosticableTreeMixin, ChangeNotifier {
/// Creates a focus node.
///
/// The [debugLabel] is ignored on release builds.
///
/// To receive key events that focuses on this node, pass a listener to
/// `onKeyEvent`.
FocusNode({
String? debugLabel,
@Deprecated(
'Use onKeyEvent instead. '
'This feature was deprecated after v3.18.0-2.0.pre.',
)
this.onKey,
this.onKeyEvent,
bool skipTraversal = false,
bool canRequestFocus = true,
bool descendantsAreFocusable = true,
bool descendantsAreTraversable = true,
}) : _skipTraversal = skipTraversal,
_canRequestFocus = canRequestFocus,
_descendantsAreFocusable = descendantsAreFocusable,
_descendantsAreTraversable = descendantsAreTraversable {
// Set it via the setter so that it does nothing on release builds.
this.debugLabel = debugLabel;
if (kFlutterMemoryAllocationsEnabled) {
ChangeNotifier.maybeDispatchObjectCreation(this);
}
}
/// If true, tells the focus traversal policy to skip over this node for
/// purposes of the traversal algorithm.
///
/// This may be used to place nodes in the focus tree that may be focused, but
/// not traversed, allowing them to receive key events as part of the focus
/// chain, but not be traversed to via focus traversal.
///
/// This is different from [canRequestFocus] because it only implies that the
/// node can't be reached via traversal, not that it can't be focused. It may
/// still be focused explicitly.
bool get skipTraversal {
if (_skipTraversal) {
return true;
}
for (final FocusNode ancestor in ancestors) {
if (!ancestor.descendantsAreTraversable) {
return true;
}
}
return false;
}
bool _skipTraversal;
set skipTraversal(bool value) {
if (value != _skipTraversal) {
_skipTraversal = value;
_manager?._markPropertiesChanged(this);
}
}
/// If true, this focus node may request the primary focus.
///
/// Defaults to true. Set to false if you want this node to do nothing when
/// [requestFocus] is called on it.
///
/// If set to false on a [FocusScopeNode], will cause all of the children of
/// the scope node to not be focusable.
///
/// If set to false on a [FocusNode], it will not affect the focusability of
/// children of the node.
///
/// The [hasFocus] member can still return true if this node is the ancestor
/// of a node with primary focus.
///
/// This is different than [skipTraversal] because [skipTraversal] still
/// allows the node to be focused, just not traversed to via the
/// [FocusTraversalPolicy].
///
/// Setting [canRequestFocus] to false implies that the node will also be
/// skipped for traversal purposes.
///
/// See also:
///
/// * [FocusTraversalGroup], a widget used to group together and configure the
/// focus traversal policy for a widget subtree.
/// * [FocusTraversalPolicy], a class that can be extended to describe a
/// traversal policy.
bool get canRequestFocus => _canRequestFocus && ancestors.every(_allowDescendantsToBeFocused);
static bool _allowDescendantsToBeFocused(FocusNode ancestor) => ancestor.descendantsAreFocusable;
bool _canRequestFocus;
@mustCallSuper
set canRequestFocus(bool value) {
if (value != _canRequestFocus) {
// Have to set this first before unfocusing, since it checks this to cull
// unfocusable, previously-focused children.
_canRequestFocus = value;
if (hasFocus && !value) {
unfocus(disposition: UnfocusDisposition.previouslyFocusedChild);
}
_manager?._markPropertiesChanged(this);
}
}
/// If false, will disable focus for all of this node's descendants.
///
/// Defaults to true. Does not affect focusability of this node: for that,
/// use [canRequestFocus].
///
/// If any descendants are focused when this is set to false, they will be
/// unfocused. When [descendantsAreFocusable] is set to true again, they will
/// not be refocused, although they will be able to accept focus again.
///
/// Does not affect the value of [canRequestFocus] on the descendants.
///
/// If a descendant node loses focus when this value is changed, the focus
/// will move to the scope enclosing this node.
///
/// See also:
///
/// * [ExcludeFocus], a widget that uses this property to conditionally
/// exclude focus for a subtree.
/// * [descendantsAreTraversable], which makes this widget's descendants
/// untraversable.
/// * [ExcludeFocusTraversal], a widget that conditionally excludes focus
/// traversal for a subtree.
/// * [Focus], a widget that exposes this setting as a parameter.
/// * [FocusTraversalGroup], a widget used to group together and configure
/// the focus traversal policy for a widget subtree that also has a
/// `descendantsAreFocusable` parameter that prevents its children from
/// being focused.
bool get descendantsAreFocusable => _descendantsAreFocusable;
bool _descendantsAreFocusable;
@mustCallSuper
set descendantsAreFocusable(bool value) {
if (value == _descendantsAreFocusable) {
return;
}
// Set _descendantsAreFocusable before unfocusing, so the scope won't try
// and focus any of the children here again if it is false.
_descendantsAreFocusable = value;
if (!value && hasFocus) {
unfocus(disposition: UnfocusDisposition.previouslyFocusedChild);
}
_manager?._markPropertiesChanged(this);
}
/// If false, tells the focus traversal policy to skip over for all of this
/// node's descendants for purposes of the traversal algorithm.
///
/// Defaults to true. Does not affect the focus traversal of this node: for
/// that, use [skipTraversal].
///
/// Does not affect the value of [FocusNode.skipTraversal] on the
/// descendants. Does not affect focusability of the descendants.
///
/// See also:
///
/// * [ExcludeFocusTraversal], a widget that uses this property to conditionally
/// exclude focus traversal for a subtree.
/// * [descendantsAreFocusable], which makes this widget's descendants
/// unfocusable.
/// * [ExcludeFocus], a widget that conditionally excludes focus for a subtree.
/// * [FocusTraversalGroup], a widget used to group together and configure
/// the focus traversal policy for a widget subtree that also has an
/// `descendantsAreFocusable` parameter that prevents its children from
/// being focused.
bool get descendantsAreTraversable => _descendantsAreTraversable;
bool _descendantsAreTraversable;
@mustCallSuper
set descendantsAreTraversable(bool value) {
if (value != _descendantsAreTraversable) {
_descendantsAreTraversable = value;
_manager?._markPropertiesChanged(this);
}
}
/// The context that was supplied to [attach].
///
/// This is typically the context for the widget that is being focused, as it
/// is used to determine the bounds of the widget.
BuildContext? get context => _context;
BuildContext? _context;
/// Called if this focus node receives a key event while focused (i.e. when
/// [hasFocus] returns true).
///
/// This property is deprecated and will be removed at a future date. Use
/// [onKeyEvent] instead.
///
/// This is a legacy API based on [RawKeyEvent] and will be deprecated in the
/// future. Prefer [onKeyEvent] instead.
///
/// {@macro flutter.widgets.FocusNode.keyEvents}
@Deprecated(
'Use onKeyEvent instead. '
'This feature was deprecated after v3.18.0-2.0.pre.',
)
FocusOnKeyCallback? onKey;
/// Called if this focus node receives a key event while focused (i.e. when
/// [hasFocus] returns true).
///
/// {@macro flutter.widgets.FocusNode.keyEvents}
FocusOnKeyEventCallback? onKeyEvent;
FocusManager? _manager;
List<FocusNode>? _ancestors;
List<FocusNode>? _descendants;
bool _hasKeyboardToken = false;
/// Returns the parent node for this object.
///
/// All nodes except for the root [FocusScopeNode] ([FocusManager.rootScope])
/// will be given a parent when they are added to the focus tree, which is
/// done using [FocusAttachment.reparent].
FocusNode? get parent => _parent;
FocusNode? _parent;
/// An iterator over the children of this node.
Iterable<FocusNode> get children => _children;
final List<FocusNode> _children = <FocusNode>[];
/// An iterator over the children that are allowed to be traversed by the
/// [FocusTraversalPolicy].
///
/// Returns the list of focusable, traversable children of this node,
/// regardless of those settings on this focus node. Will return an empty
/// iterable if [descendantsAreFocusable] is false.
///
/// See also
///
/// * [traversalDescendants], which traverses all of the node's descendants,
/// not just the immediate children.
Iterable<FocusNode> get traversalChildren {
if (!descendantsAreFocusable) {
return const Iterable<FocusNode>.empty();
}
return children.where(
(FocusNode node) => !node.skipTraversal && node.canRequestFocus,
);
}
/// A debug label that is used for diagnostic output.
///
/// Will always return null in release builds.
String? get debugLabel => _debugLabel;
String? _debugLabel;
set debugLabel(String? value) {
assert(() {
// Only set the value in debug builds.
_debugLabel = value;
return true;
}());
}
FocusAttachment? _attachment;
/// An [Iterable] over the hierarchy of children below this one, in
/// depth-first order.
Iterable<FocusNode> get descendants {
if (_descendants == null) {
final List<FocusNode> result = <FocusNode>[];
for (final FocusNode child in _children) {
result.addAll(child.descendants);
result.add(child);
}
_descendants = result;
}
return _descendants!;
}
/// Returns all descendants which do not have the [skipTraversal] and do have
/// the [canRequestFocus] flag set.
Iterable<FocusNode> get traversalDescendants {
if (!descendantsAreFocusable) {
return const Iterable<FocusNode>.empty();
}
return descendants.where((FocusNode node) => !node.skipTraversal && node.canRequestFocus);
}
/// An [Iterable] over the ancestors of this node.
///
/// Iterates the ancestors of this node starting at the parent and iterating
/// over successively more remote ancestors of this node, ending at the root
/// [FocusScopeNode] ([FocusManager.rootScope]).
Iterable<FocusNode> get ancestors {
if (_ancestors == null) {
final List<FocusNode> result = <FocusNode>[];
FocusNode? parent = _parent;
while (parent != null) {
result.add(parent);
parent = parent._parent;
}
_ancestors = result;
}
return _ancestors!;
}
/// Whether this node has input focus.
///
/// A [FocusNode] has focus when it is an ancestor of a node that returns true
/// from [hasPrimaryFocus], or it has the primary focus itself.
///
/// The [hasFocus] accessor is different from [hasPrimaryFocus] in that
/// [hasFocus] is true if the node is anywhere in the focus chain, but for
/// [hasPrimaryFocus] the node must to be at the end of the chain to return
/// true.
///
/// A node that returns true for [hasFocus] will receive key events if none of
/// its focused descendants returned true from their [onKey] handler.
///
/// This object is a [ChangeNotifier], and notifies its [Listenable] listeners
/// (registered via [addListener]) whenever this value changes.
///
/// See also:
///
/// * [Focus.isAt], which is a static method that will return the focus
/// state of the nearest ancestor [Focus] widget's focus node.
bool get hasFocus => hasPrimaryFocus || (_manager?.primaryFocus?.ancestors.contains(this) ?? false);
/// Returns true if this node currently has the application-wide input focus.
///
/// A [FocusNode] has the primary focus when the node is focused in its
/// nearest ancestor [FocusScopeNode] and [hasFocus] is true for all its
/// ancestor nodes, but none of its descendants.
///
/// This is different from [hasFocus] in that [hasFocus] is true if the node
/// is anywhere in the focus chain, but here the node has to be at the end of
/// the chain to return true.
///
/// A node that returns true for [hasPrimaryFocus] will be the first node to
/// receive key events through its [onKey] handler.
///
/// This object notifies its listeners whenever this value changes.
bool get hasPrimaryFocus => _manager?.primaryFocus == this;
/// Returns the [FocusHighlightMode] that is currently in effect for this node.
FocusHighlightMode get highlightMode => FocusManager.instance.highlightMode;
/// Returns the nearest enclosing scope node above this node, including
/// this node, if it's a scope.
///
/// Returns null if no scope is found.
///
/// Use [enclosingScope] to look for scopes above this node.
FocusScopeNode? get nearestScope => enclosingScope;
FocusScopeNode? _enclosingScope;
void _clearEnclosingScopeCache() {
final FocusScopeNode? cachedScope = _enclosingScope;
if (cachedScope == null) {
return;
}
_enclosingScope = null;
if (children.isNotEmpty) {
for (final FocusNode child in children) {
if (identical(cachedScope, child._enclosingScope)) {
child._clearEnclosingScopeCache();
}
}
}
}
/// Returns the nearest enclosing scope node above this node, or null if the
/// node has not yet be added to the focus tree.
///
/// If this node is itself a scope, this will only return ancestors of this
/// scope.
///
/// Use [nearestScope] to start at this node instead of above it.
FocusScopeNode? get enclosingScope {
final FocusScopeNode? enclosingScope = _enclosingScope ??= parent?.nearestScope;
assert(enclosingScope == parent?.nearestScope, '$this has invalid scope cache: $_enclosingScope != ${parent?.nearestScope}');
return enclosingScope;
}
/// Returns the size of the attached widget's [RenderObject], in logical
/// units.
///
/// Size is the size of the transformed widget in global coordinates.
Size get size => rect.size;
/// Returns the global offset to the upper left corner of the attached
/// widget's [RenderObject], in logical units.
///
/// Offset is the offset of the transformed widget in global coordinates.
Offset get offset {
assert(
context != null,
"Tried to get the offset of a focus node that didn't have its context set yet.\n"
'The context needs to be set before trying to evaluate traversal policies. '
'Setting the context is typically done with the attach method.',
);
final RenderObject object = context!.findRenderObject()!;
return MatrixUtils.transformPoint(object.getTransformTo(null), object.semanticBounds.topLeft);
}
/// Returns the global rectangle of the attached widget's [RenderObject], in
/// logical units.
///
/// Rect is the rectangle of the transformed widget in global coordinates.
Rect get rect {
assert(
context != null,
"Tried to get the bounds of a focus node that didn't have its context set yet.\n"
'The context needs to be set before trying to evaluate traversal policies. '
'Setting the context is typically done with the attach method.',
);
final RenderObject object = context!.findRenderObject()!;
final Offset topLeft = MatrixUtils.transformPoint(object.getTransformTo(null), object.semanticBounds.topLeft);
final Offset bottomRight = MatrixUtils.transformPoint(object.getTransformTo(null), object.semanticBounds.bottomRight);
return Rect.fromLTRB(topLeft.dx, topLeft.dy, bottomRight.dx, bottomRight.dy);
}
/// Removes the focus on this node by moving the primary focus to another node.
///
/// This method removes focus from a node that has the primary focus, cancels
/// any outstanding requests to focus it, while setting the primary focus to
/// another node according to the `disposition`.
///
/// It is safe to call regardless of whether this node has ever requested
/// focus or not. If this node doesn't have focus or primary focus, nothing
/// happens.
///
/// The `disposition` argument determines which node will receive primary
/// focus after this one loses it.
///
/// If `disposition` is set to [UnfocusDisposition.scope] (the default), then
/// the previously focused node history of the enclosing scope will be
/// cleared, and the primary focus will be moved to the nearest enclosing
/// scope ancestor that is enabled for focus, ignoring the
/// [FocusScopeNode.focusedChild] for that scope.
///
/// If `disposition` is set to [UnfocusDisposition.previouslyFocusedChild],
/// then this node will be removed from the previously focused list in the
/// [enclosingScope], and the focus will be moved to the previously focused
/// node of the [enclosingScope], which (if it is a scope itself), will find
/// its focused child, etc., until a leaf focus node is found. If there is no
/// previously focused child, then the scope itself will receive focus, as if
/// [UnfocusDisposition.scope] were specified.
///
/// If you want this node to lose focus and the focus to move to the next or
/// previous node in the enclosing [FocusTraversalGroup], call [nextFocus] or
/// [previousFocus] instead of calling [unfocus].
///
/// {@tool dartpad}
/// This example shows the difference between the different [UnfocusDisposition]
/// values for [unfocus].
///
/// Try setting focus on the four text fields by selecting them, and then
/// select "UNFOCUS" to see what happens when the current
/// [FocusManager.primaryFocus] is unfocused.
///
/// Try pressing the TAB key after unfocusing to see what the next widget
/// chosen is.
///
/// ** See code in examples/api/lib/widgets/focus_manager/focus_node.unfocus.0.dart **
/// {@end-tool}
void unfocus({
UnfocusDisposition disposition = UnfocusDisposition.scope,
}) {
if (!hasFocus && (_manager == null || _manager!._markedForFocus != this)) {
return;
}
FocusScopeNode? scope = enclosingScope;
if (scope == null) {
// If the scope is null, then this is either the root node, or a node that
// is not yet in the tree, neither of which do anything when unfocused.
return;
}
switch (disposition) {
case UnfocusDisposition.scope:
// If it can't request focus, then don't modify its focused children.
if (scope.canRequestFocus) {
// Clearing the focused children here prevents re-focusing the node
// that we just unfocused if we immediately hit "next" after
// unfocusing, and also prevents choosing to refocus the next-to-last
// focused child if unfocus is called more than once.
scope._focusedChildren.clear();
}
while (!scope!.canRequestFocus) {
scope = scope.enclosingScope ?? _manager?.rootScope;
}
scope._doRequestFocus(findFirstFocus: false);
case UnfocusDisposition.previouslyFocusedChild:
// Select the most recent focused child from the nearest focusable scope
// and focus that. If there isn't one, focus the scope itself.
if (scope.canRequestFocus) {
scope._focusedChildren.remove(this);
}
while (!scope!.canRequestFocus) {
scope.enclosingScope?._focusedChildren.remove(scope);
scope = scope.enclosingScope ?? _manager?.rootScope;
}
scope._doRequestFocus(findFirstFocus: true);
}
assert(_focusDebug(() => 'Unfocused node:', () => <Object>['primary focus was $this', 'next focus will be ${_manager?._markedForFocus}']));
}
/// Removes the keyboard token from this focus node if it has one.
///
/// This mechanism helps distinguish between an input control gaining focus by
/// default and gaining focus as a result of an explicit user action.
///
/// When a focus node requests the focus (either via
/// [FocusScopeNode.requestFocus] or [FocusScopeNode.autofocus]), the focus
/// node receives a keyboard token if it does not already have one. Later,
/// when the focus node becomes focused, the widget that manages the
/// [TextInputConnection] should show the keyboard (i.e. call
/// [TextInputConnection.show]) only if it successfully consumes the keyboard
/// token from the focus node.
///
/// Returns true if this method successfully consumes the keyboard token.
bool consumeKeyboardToken() {
if (!_hasKeyboardToken) {
return false;
}
_hasKeyboardToken = false;
return true;
}
// Marks the node as being the next to be focused, meaning that it will become
// the primary focus and notify listeners of a focus change the next time
// focus is resolved by the manager. If something else calls _markNextFocus
// before then, then that node will become the next focus instead of the
// previous one.
void _markNextFocus(FocusNode newFocus) {
if (_manager != null) {
// If we have a manager, then let it handle the focus change.
_manager!._markNextFocus(this);
return;
}
// If we don't have a manager, then change the focus locally.
newFocus._setAsFocusedChildForScope();
newFocus._notify();
if (newFocus != this) {
_notify();
}
}
// Removes the given FocusNode and its children as a child of this node.
@mustCallSuper
void _removeChild(FocusNode node, {bool removeScopeFocus = true}) {
assert(_children.contains(node), "Tried to remove a node that wasn't a child.");
assert(node._parent == this);
assert(node._manager == _manager);
if (removeScopeFocus) {
final FocusScopeNode? nodeScope = node.enclosingScope;
if (nodeScope != null) {
nodeScope._focusedChildren.remove(node);
node.descendants.where((FocusNode descendant) {
return descendant.enclosingScope == nodeScope;
}).forEach(nodeScope._focusedChildren.remove);
}
}
node._parent = null;
node._clearEnclosingScopeCache();
_children.remove(node);
for (final FocusNode ancestor in ancestors) {
ancestor._descendants = null;
}
_descendants = null;
assert(_manager == null || !_manager!.rootScope.descendants.contains(node));
}