focus_scope.dart 36.1 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
Ian Hickson's avatar
Ian Hickson committed
4

5
import 'package:flutter/foundation.dart';
6 7 8 9

import 'basic.dart';
import 'focus_manager.dart';
import 'framework.dart';
10
import 'inherited_notifier.dart';
11

12 13
/// A widget that manages a [FocusNode] to allow keyboard focus to be given
/// to this widget and its descendants.
14
///
15 16
/// {@youtube 560 315 https://www.youtube.com/watch?v=JCDfh5bs1xc}
///
17
/// When the focus is gained or lost, [onFocusChange] is called.
18
///
19 20 21 22
/// For keyboard events, [onKey] and [onKeyEvent] are called if
/// [FocusNode.hasFocus] is true for this widget's [focusNode], unless a focused
/// descendant's [onKey] or [onKeyEvent] callback returned
/// [KeyEventResult.handled] when called.
Adam Barth's avatar
Adam Barth committed
23
///
24
/// This widget does not provide any visual indication that the focus has
25
/// changed. Any desired visual changes should be made when [onFocusChange] is
26 27 28 29 30 31 32
/// called.
///
/// To access the [FocusNode] of the nearest ancestor [Focus] widget and
/// establish a relationship that will rebuild the widget when the focus
/// changes, use the [Focus.of] and [FocusScope.of] static methods.
///
/// To access the focused state of the nearest [Focus] widget, use
33 34 35
/// [FocusNode.hasFocus] from a build method, which also establishes a
/// relationship between the calling widget and the [Focus] widget that will
/// rebuild the calling widget when the focus changes.
36 37 38
///
/// Managing a [FocusNode] means managing its lifecycle, listening for changes
/// in focus, and re-parenting it when needed to keep the focus hierarchy in
39 40 41 42 43
/// sync with the widget hierarchy. This widget does all of those things for
/// you. See [FocusNode] for more information about the details of what node
/// management entails if you are not using a [Focus] widget and you need to do
/// it yourself.
///
44 45 46 47 48 49 50 51 52 53 54 55
/// If the [Focus] default constructor is used, then this widget will manage any
/// given [focusNode] by overwriting the appropriate values of the [focusNode]
/// with the values of [FocusNode.onKey], [FocusNode.onKeyEvent],
/// [FocusNode.skipTraversal], [FocusNode.canRequestFocus], and
/// [FocusNode.descendantsAreFocusable] whenever the [Focus] widget is updated.
///
/// If the [Focus.withExternalFocusNode] is used instead, then the values
/// returned by [onKey], [onKeyEvent], [skipTraversal], [canRequestFocus], and
/// [descendantsAreFocusable] will be the values in the external focus node, and
/// the external focus node's values will not be overwritten when the widget is
/// updated.
///
56 57 58 59
/// To collect a sub-tree of nodes into an exclusive group that restricts focus
/// traversal to the group, use a [FocusScope]. To collect a sub-tree of nodes
/// into a group that has a specific order to its traversal but allows the
/// traversal to escape the group, use a [FocusTraversalGroup].
60
///
61 62 63 64
/// To move the focus, use methods on [FocusNode] by getting the [FocusNode]
/// through the [of] method. For instance, to move the focus to the next node in
/// the focus traversal order, call `Focus.of(context).nextFocus()`. To unfocus
/// a widget, call `Focus.of(context).unfocus()`.
65
///
66
/// {@tool dartpad}
67 68 69 70
/// This example shows how to manage focus using the [Focus] and [FocusScope]
/// widgets. See [FocusNode] for a similar example that doesn't use [Focus] or
/// [FocusScope].
///
71
/// ** See code in examples/api/lib/widgets/focus_scope/focus.0.dart **
72
/// {@end-tool}
Adam Barth's avatar
Adam Barth committed
73
///
74
/// {@tool dartpad}
75 76 77 78 79 80 81 82
/// This example shows how to wrap another widget in a [Focus] widget to make it
/// focusable. It wraps a [Container], and changes the container's color when it
/// is set as the [FocusManager.primaryFocus].
///
/// If you also want to handle mouse hover and/or keyboard actions on a widget,
/// consider using a [FocusableActionDetector], which combines several different
/// widgets to provide those capabilities.
///
83
/// ** See code in examples/api/lib/widgets/focus_scope/focus.1.dart **
84 85
/// {@end-tool}
///
86
/// {@tool dartpad}
87 88 89 90 91 92 93
/// This example shows how to focus a newly-created widget immediately after it
/// is created.
///
/// The focus node will not actually be given the focus until after the frame in
/// which it has requested focus is drawn, so it is OK to call
/// [FocusNode.requestFocus] on a node which is not yet in the focus tree.
///
94
/// ** See code in examples/api/lib/widgets/focus_scope/focus.2.dart **
95 96
/// {@end-tool}
///
97
/// See also:
Adam Barth's avatar
Adam Barth committed
98
///
99 100 101 102 103 104 105 106 107 108 109
///  * [FocusNode], which represents a node in the focus hierarchy and
///    [FocusNode]'s API documentation includes a detailed explanation of its role
///    in the overall focus system.
///  * [FocusScope], a widget that manages a group of focusable widgets using a
///    [FocusScopeNode].
///  * [FocusScopeNode], a node that collects focus nodes into a group for
///    traversal.
///  * [FocusManager], a singleton that manages the primary focus and
///    distributes key events to focused nodes.
///  * [FocusTraversalPolicy], an object used to determine how to move the focus
///    to other nodes.
110 111
///  * [FocusTraversalGroup], a widget that groups together and imposes a
///    traversal policy on the [Focus] nodes below it in the widget hierarchy.
112 113
class Focus extends StatefulWidget {
  /// Creates a widget that manages a [FocusNode].
114
  ///
115 116
  /// The [child] argument is required and must not be null.
  ///
117
  /// The [autofocus] argument must not be null.
118
  const Focus({
119
    super.key,
120
    required this.child,
121
    this.focusNode,
122
    this.parentNode,
123
    this.autofocus = false,
124
    this.onFocusChange,
125 126 127 128 129
    FocusOnKeyEventCallback? onKeyEvent,
    FocusOnKeyCallback? onKey,
    bool? canRequestFocus,
    bool? skipTraversal,
    bool? descendantsAreFocusable,
130
    bool? descendantsAreTraversable,
131
    this.includeSemantics = true,
132 133 134 135 136 137
    String? debugLabel,
  })  : _onKeyEvent = onKeyEvent,
        _onKey = onKey,
        _canRequestFocus = canRequestFocus,
        _skipTraversal = skipTraversal,
        _descendantsAreFocusable = descendantsAreFocusable,
138
        _descendantsAreTraversable = descendantsAreTraversable,
139 140
        _debugLabel = debugLabel,
        assert(child != null),
141
        assert(autofocus != null),
142
        assert(includeSemantics != null);
143

144 145 146 147 148 149
  /// Creates a Focus widget that uses the given [focusNode] as the source of
  /// truth for attributes on the node, rather than the attributes of this widget.
  const factory Focus.withExternalFocusNode({
    Key? key,
    required Widget child,
    required FocusNode focusNode,
150
    FocusNode? parentNode,
151 152 153 154 155 156 157 158
    bool autofocus,
    ValueChanged<bool>? onFocusChange,
    bool includeSemantics,
  }) = _FocusWithExternalFocusNode;

  // Indicates whether the widget's focusNode attributes should have priority
  // when then widget is updated.
  bool get _usingExternalFocus => false;
159

160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
  /// The optional parent node to use when reparenting the [focusNode] for this
  /// [Focus] widget.
  ///
  /// If [parentNode] is null, then [Focus.maybeOf] is used to find the parent
  /// in the widget tree, which is typically what is desired, since it is easier
  /// to reason about the focus tree if it mirrors the shape of the widget tree.
  ///
  /// Set this property if the focus tree needs to have a different shape than
  /// the widget tree. This is typically in cases where a dialog is in an
  /// [Overlay] (or another part of the widget tree), and focus should
  /// behave as if the widgets in the overlay are descendants of the given
  /// [parentNode] for purposes of focus.
  ///
  /// Defaults to null.
  final FocusNode? parentNode;

176
  /// The child widget of this [Focus].
177
  ///
178
  /// {@macro flutter.widgets.ProxyWidget.child}
179
  final Widget child;
180

181 182 183 184 185
  /// {@template flutter.widgets.Focus.focusNode}
  /// An optional focus node to use as the focus node for this widget.
  ///
  /// If one is not supplied, then one will be automatically allocated, owned,
  /// and managed by this widget. The widget will be focusable even if a
186
  /// [focusNode] is not supplied. If supplied, the given [focusNode] will be
187 188 189 190 191 192 193 194 195 196 197
  /// _hosted_ by this widget, but not owned. See [FocusNode] for more
  /// information on what being hosted and/or owned implies.
  ///
  /// Supplying a focus node is sometimes useful if an ancestor to this widget
  /// wants to control when this widget has the focus. The owner will be
  /// responsible for calling [FocusNode.dispose] on the focus node when it is
  /// done with it, but this widget will attach/detach and reparent the node
  /// when needed.
  /// {@endtemplate}
  ///
  /// A non-null [focusNode] must be supplied if using the
198
  /// [Focus.withExternalFocusNode] constructor.
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
  final FocusNode? focusNode;

  /// {@template flutter.widgets.Focus.autofocus}
  /// True if this widget will be selected as the initial focus when no other
  /// node in its scope is currently focused.
  ///
  /// Ideally, there is only one widget with autofocus set in each [FocusScope].
  /// If there is more than one widget with autofocus set, then the first one
  /// added to the tree will get focus.
  ///
  /// Must not be null. Defaults to false.
  /// {@endtemplate}
  final bool autofocus;

  /// Handler called when the focus changes.
  ///
  /// Called with true if this widget's node gains focus, and false if it loses
216
  /// focus.
217 218 219 220
  final ValueChanged<bool>? onFocusChange;

  /// A handler for keys that are pressed when this object or one of its
  /// children has focus.
221
  ///
222
  /// Key events are first given to the [FocusNode] that has primary focus, and
223 224 225
  /// if its [onKeyEvent] method returns [KeyEventResult.ignored], then they are
  /// given to each ancestor node up the focus hierarchy in turn. If an event
  /// reaches the root of the hierarchy, it is discarded.
226 227 228 229 230 231
  ///
  /// This is not the way to get text input in the manner of a text field: it
  /// leaves out support for input method editors, and doesn't support soft
  /// keyboards in general. For text input, consider [TextField],
  /// [EditableText], or [CupertinoTextField] instead, which do support these
  /// things.
232 233
  FocusOnKeyEventCallback? get onKeyEvent => _onKeyEvent ?? focusNode?.onKeyEvent;
  final FocusOnKeyEventCallback? _onKeyEvent;
234

235 236
  /// A handler for keys that are pressed when this object or one of its
  /// children has focus.
237 238 239 240 241
  ///
  /// This is a legacy API based on [RawKeyEvent] and will be deprecated in the
  /// future. Prefer [onKeyEvent] instead.
  ///
  /// Key events are first given to the [FocusNode] that has primary focus, and
242 243 244 245 246 247 248 249 250
  /// if its [onKey] method return false, then they are given to each ancestor
  /// node up the focus hierarchy in turn. If an event reaches the root of the
  /// hierarchy, it is discarded.
  ///
  /// This is not the way to get text input in the manner of a text field: it
  /// leaves out support for input method editors, and doesn't support soft
  /// keyboards in general. For text input, consider [TextField],
  /// [EditableText], or [CupertinoTextField] instead, which do support these
  /// things.
251 252
  FocusOnKeyCallback? get onKey => _onKey ?? focusNode?.onKey;
  final FocusOnKeyCallback? _onKey;
253

254
  /// {@template flutter.widgets.Focus.canRequestFocus}
255 256
  /// If true, this widget may request the primary focus.
  ///
257
  /// Defaults to true. Set to false if you want the [FocusNode] this widget
258 259 260
  /// manages to do nothing when [FocusNode.requestFocus] is called on it. Does
  /// not affect the children of this node, and [FocusNode.hasFocus] can still
  /// return true if this node is the ancestor of the primary focus.
261
  ///
262 263
  /// This is different than [Focus.skipTraversal] because [Focus.skipTraversal]
  /// still allows the widget to be focused, just not traversed to.
264
  ///
265 266
  /// Setting [FocusNode.canRequestFocus] to false implies that the widget will
  /// also be skipped for traversal purposes.
267 268 269
  ///
  /// See also:
  ///
270 271 272 273
  /// * [FocusTraversalGroup], a widget that sets the traversal policy for its
  ///   descendants.
  /// * [FocusTraversalPolicy], a class that can be extended to describe a
  ///   traversal policy.
274
  /// {@endtemplate}
275 276 277 278 279 280 281 282 283 284 285 286 287 288
  bool get canRequestFocus => _canRequestFocus ?? focusNode?.canRequestFocus ?? true;
  final bool? _canRequestFocus;

  /// Sets the [FocusNode.skipTraversal] flag on the focus node so that it won't
  /// be visited by the [FocusTraversalPolicy].
  ///
  /// This is sometimes useful if a [Focus] widget should receive key events as
  /// part of the focus chain, but shouldn't be accessible via focus traversal.
  ///
  /// This is different from [FocusNode.canRequestFocus] because it only implies
  /// that the widget can't be reached via traversal, not that it can't be
  /// focused. It may still be focused explicitly.
  bool get skipTraversal => _skipTraversal ?? focusNode?.skipTraversal ?? false;
  final bool? _skipTraversal;
289

290 291 292 293
  /// {@template flutter.widgets.Focus.descendantsAreFocusable}
  /// If false, will make this widget's descendants unfocusable.
  ///
  /// Defaults to true. Does not affect focusability of this node (just its
294
  /// descendants): for that, use [FocusNode.canRequestFocus].
295 296
  ///
  /// If any descendants are focused when this is set to false, they will be
297
  /// unfocused. When [descendantsAreFocusable] is set to true again, they will
298 299
  /// not be refocused, although they will be able to accept focus again.
  ///
300 301
  /// Does not affect the value of [FocusNode.canRequestFocus] on the
  /// descendants.
302
  ///
303 304 305
  /// If a descendant node loses focus when this value is changed, the focus
  /// will move to the scope enclosing this node.
  ///
306 307
  /// See also:
  ///
308 309
  /// * [ExcludeFocus], a widget that uses this property to conditionally
  ///   exclude focus for a subtree.
310 311 312 313
  /// * [descendantsAreTraversable], which makes this widget's descendants
  ///   untraversable.
  /// * [ExcludeFocusTraversal], a widget that conditionally excludes focus
  ///   traversal for a subtree.
314 315 316 317
  /// * [FocusTraversalGroup], a widget used to group together and configure the
  ///   focus traversal policy for a widget subtree that has a
  ///   `descendantsAreFocusable` parameter to conditionally block focus for a
  ///   subtree.
318
  /// {@endtemplate}
319 320 321
  bool get descendantsAreFocusable => _descendantsAreFocusable ?? focusNode?.descendantsAreFocusable ?? true;
  final bool? _descendantsAreFocusable;

322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345
  /// {@template flutter.widgets.Focus.descendantsAreTraversable}
  /// If false, will make this widget's descendants untraversable.
  ///
  /// Defaults to true. Does not affect traversablility of this node (just its
  /// descendants): for that, use [FocusNode.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 has a
  ///   `descendantsAreFocusable` parameter to conditionally block focus for a
  ///   subtree.
  /// {@endtemplate}
  bool get descendantsAreTraversable => _descendantsAreTraversable ?? focusNode?.descendantsAreTraversable ?? true;
  final bool? _descendantsAreTraversable;

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
  /// {@template flutter.widgets.Focus.includeSemantics}
  /// Include semantics information in this widget.
  ///
  /// If true, this widget will include a [Semantics] node that indicates the
  /// [SemanticsProperties.focusable] and [SemanticsProperties.focused]
  /// properties.
  ///
  /// It is not typical to set this to false, as that can affect the semantics
  /// information available to accessibility systems.
  ///
  /// Must not be null, defaults to true.
  /// {@endtemplate}
  final bool includeSemantics;

  /// A debug label for this widget.
  ///
  /// Not used for anything except to be printed in the diagnostic output from
  /// [toString] or [toStringDeep].
  ///
  /// To get a string with the entire tree, call [debugDescribeFocusTree]. To
  /// print it to the console call [debugDumpFocusTree].
  ///
  /// Defaults to null.
  String? get debugLabel => _debugLabel ?? focusNode?.debugLabel;
  final String? _debugLabel;
371

372 373
  /// Returns the [focusNode] of the [Focus] that most tightly encloses the
  /// given [BuildContext].
374
  ///
375 376
  /// If no [Focus] node is found before reaching the nearest [FocusScope]
  /// widget, or there is no [Focus] widget in scope, then this method will
377
  /// throw an exception.
378
  ///
379
  /// The `context` and `scopeOk` arguments must not be null.
380 381 382
  ///
  /// Calling this function creates a dependency that will rebuild the given
  /// context when the focus changes.
383 384 385 386 387 388
  ///
  /// See also:
  ///
  ///  * [maybeOf], which is similar to this function, but will return null
  ///    instead of throwing if it doesn't find a [Focus] node.
  static FocusNode of(BuildContext context, { bool scopeOk = false }) {
389
    assert(context != null);
390
    assert(scopeOk != null);
391
    final _FocusInheritedScope? marker = context.dependOnInheritedWidgetOfExactType<_FocusInheritedScope>();
392
    final FocusNode? node = marker?.notifier;
393 394
    assert(() {
      if (node == null) {
395
        throw FlutterError(
396 397 398 399 400
          'Focus.of() was called with a context that does not contain a Focus widget.\n'
          'No Focus widget ancestor could be found starting from the context that was passed to '
          'Focus.of(). This can happen because you are using a widget that looks for a Focus '
          'ancestor, and do not have a Focus widget descendant in the nearest FocusScope.\n'
          'The context used was:\n'
401
          '  $context',
402 403
        );
      }
404 405 406 407
      return true;
    }());
    assert(() {
      if (!scopeOk && node is FocusScopeNode) {
408
        throw FlutterError(
409 410 411 412 413 414 415
          'Focus.of() was called with a context that does not contain a Focus between the given '
          'context and the nearest FocusScope widget.\n'
          'No Focus ancestor could be found starting from the context that was passed to '
          'Focus.of() to the point where it found the nearest FocusScope widget. This can happen '
          'because you are using a widget that looks for a Focus ancestor, and do not have a '
          'Focus widget ancestor in the current FocusScope.\n'
          'The context used was:\n'
416
          '  $context',
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
      return true;
    }());
    return node!;
  }

  /// Returns the [focusNode] of the [Focus] that most tightly encloses the
  /// given [BuildContext].
  ///
  /// If no [Focus] node is found before reaching the nearest [FocusScope]
  /// widget, or there is no [Focus] widget in scope, then this method will
  /// return null.
  ///
  /// The `context` and `scopeOk` arguments must not be null.
  ///
  /// Calling this function creates a dependency that will rebuild the given
  /// context when the focus changes.
  ///
  /// See also:
  ///
  ///  * [of], which is similar to this function, but will throw an exception if
  ///    it doesn't find a [Focus] node instead of returning null.
  static FocusNode? maybeOf(BuildContext context, { bool scopeOk = false }) {
    assert(context != null);
    assert(scopeOk != null);
443
    final _FocusInheritedScope? marker = context.dependOnInheritedWidgetOfExactType<_FocusInheritedScope>();
444 445 446 447 448
    final FocusNode? node = marker?.notifier;
    if (node == null) {
      return null;
    }
    if (!scopeOk && node is FocusScopeNode) {
449 450 451
      return null;
    }
    return node;
452 453
  }

454 455 456
  /// Returns true if the nearest enclosing [Focus] widget's node is focused.
  ///
  /// A convenience method to allow build methods to write:
457 458 459 460 461 462
  /// `Focus.isAt(context)` to get whether or not the nearest [Focus] above them
  /// in the widget hierarchy currently has the input focus.
  ///
  /// Returns false if no [Focus] widget is found before reaching the nearest
  /// [FocusScope], or if the root of the focus tree is reached without finding
  /// a [Focus] widget.
463 464 465
  ///
  /// Calling this function creates a dependency that will rebuild the given
  /// context when the focus changes.
466
  static bool isAt(BuildContext context) => Focus.maybeOf(context)?.hasFocus ?? false;
467

468
  @override
469 470 471 472
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
    properties.add(StringProperty('debugLabel', debugLabel, defaultValue: null));
    properties.add(FlagProperty('autofocus', value: autofocus, ifTrue: 'AUTOFOCUS', defaultValue: false));
473 474
    properties.add(FlagProperty('canRequestFocus', value: canRequestFocus, ifFalse: 'NOT FOCUSABLE', defaultValue: false));
    properties.add(FlagProperty('descendantsAreFocusable', value: descendantsAreFocusable, ifFalse: 'DESCENDANTS UNFOCUSABLE', defaultValue: true));
475
    properties.add(FlagProperty('descendantsAreTraversable', value: descendantsAreTraversable, ifFalse: 'DESCENDANTS UNTRAVERSABLE', defaultValue: true));
476
    properties.add(DiagnosticsProperty<FocusNode>('focusNode', focusNode, defaultValue: null));
477 478 479
  }

  @override
480
  State<Focus> createState() => _FocusState();
481 482
}

483 484 485 486
// Implements the behavior differences when the Focus.withExternalFocusNode
// constructor is used.
class _FocusWithExternalFocusNode extends Focus {
  const _FocusWithExternalFocusNode({
487 488 489
    super.key,
    required super.child,
    required FocusNode super.focusNode,
490
    super.parentNode,
491 492 493 494
    super.autofocus,
    super.onFocusChange,
    super.includeSemantics,
  });
495 496 497 498 499 500 501 502 503 504 505 506 507 508

  @override
  bool get _usingExternalFocus => true;
  @override
  FocusOnKeyEventCallback? get onKeyEvent => focusNode!.onKeyEvent;
  @override
  FocusOnKeyCallback? get onKey => focusNode!.onKey;
  @override
  bool get canRequestFocus => focusNode!.canRequestFocus;
  @override
  bool get skipTraversal => focusNode!.skipTraversal;
  @override
  bool get descendantsAreFocusable => focusNode!.descendantsAreFocusable;
  @override
509 510
  bool? get _descendantsAreTraversable => focusNode!.descendantsAreTraversable;
  @override
511 512 513
  String? get debugLabel => focusNode!.debugLabel;
}

514
class _FocusState extends State<Focus> {
515 516
  FocusNode? _internalNode;
  FocusNode get focusNode => widget.focusNode ?? _internalNode!;
517 518 519
  late bool _hadPrimaryFocus;
  late bool _couldRequestFocus;
  late bool _descendantsWereFocusable;
520
  late bool _descendantsWereTraversable;
521
  bool _didAutofocus = false;
522
  FocusAttachment? _focusAttachment;
523 524 525 526 527 528 529 530 531 532

  @override
  void initState() {
    super.initState();
    _initNode();
  }

  void _initNode() {
    if (widget.focusNode == null) {
      // Only create a new node if the widget doesn't have one.
533 534
      // This calls a function instead of just allocating in place because
      // _createNode is overridden in _FocusScopeState.
535 536
      _internalNode ??= _createNode();
    }
537
    focusNode.descendantsAreFocusable = widget.descendantsAreFocusable;
538
    focusNode.descendantsAreTraversable = widget.descendantsAreTraversable;
539
    if (widget.skipTraversal != null) {
540
      focusNode.skipTraversal = widget.skipTraversal;
541
    }
542 543
    if (widget._canRequestFocus != null) {
      focusNode.canRequestFocus = widget._canRequestFocus!;
544
    }
545 546
    _couldRequestFocus = focusNode.canRequestFocus;
    _descendantsWereFocusable = focusNode.descendantsAreFocusable;
547
    _descendantsWereTraversable = focusNode.descendantsAreTraversable;
548
    _hadPrimaryFocus = focusNode.hasPrimaryFocus;
549
    _focusAttachment = focusNode.attach(context, onKeyEvent: widget.onKeyEvent, onKey: widget.onKey);
550

551
    // Add listener even if the _internalNode existed before, since it should
552
    // not be listening now if we're re-using a previous one because it should
553
    // have already removed its listener.
554
    focusNode.addListener(_handleFocusChanged);
555 556
  }

557 558 559
  FocusNode _createNode() {
    return FocusNode(
      debugLabel: widget.debugLabel,
560
      canRequestFocus: widget.canRequestFocus,
561
      descendantsAreFocusable: widget.descendantsAreFocusable,
562
      descendantsAreTraversable: widget.descendantsAreTraversable,
563
      skipTraversal: widget.skipTraversal,
564 565
    );
  }
566 567 568 569 570

  @override
  void dispose() {
    // Regardless of the node owner, we need to remove it from the tree and stop
    // listening to it.
571
    focusNode.removeListener(_handleFocusChanged);
572
    _focusAttachment!.detach();
573

574 575 576 577 578
    // Don't manage the lifetime of external nodes given to the widget, just the
    // internal node.
    _internalNode?.dispose();
    super.dispose();
  }
579 580 581 582

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
583
    _focusAttachment?.reparent();
584 585 586 587
    _handleAutofocus();
  }

  void _handleAutofocus() {
588
    if (!_didAutofocus && widget.autofocus) {
589
      FocusScope.of(context).autofocus(focusNode);
590 591 592 593 594
      _didAutofocus = true;
    }
  }

  @override
595 596
  void deactivate() {
    super.deactivate();
597 598 599 600 601 602 603
    // The focus node's location in the tree is no longer valid here. But
    // we can't unfocus or remove the node from the tree because if the widget
    // is moved to a different part of the tree (via global key) it should
    // retain its focus state. That's why we temporarily park it on the root
    // focus node (via reparent) until it either gets moved to a different part
    // of the tree (via didChangeDependencies) or until it is disposed.
    _focusAttachment?.reparent();
604 605 606 607 608 609
    _didAutofocus = false;
  }

  @override
  void didUpdateWidget(Focus oldWidget) {
    super.didUpdateWidget(oldWidget);
610
    assert(() {
611 612 613 614 615
      // Only update the debug label in debug builds.
      if (oldWidget.focusNode == widget.focusNode &&
          !widget._usingExternalFocus &&
          oldWidget.debugLabel != widget.debugLabel) {
        focusNode.debugLabel = widget.debugLabel;
616 617 618 619 620
      }
      return true;
    }());

    if (oldWidget.focusNode == widget.focusNode) {
621 622 623 624 625 626 627 628 629 630
      if (!widget._usingExternalFocus) {
        if (widget.onKey != focusNode.onKey) {
          focusNode.onKey = widget.onKey;
        }
        if (widget.onKeyEvent != focusNode.onKeyEvent) {
          focusNode.onKeyEvent = widget.onKeyEvent;
        }
        if (widget.skipTraversal != null) {
          focusNode.skipTraversal = widget.skipTraversal;
        }
631 632
        if (widget._canRequestFocus != null) {
          focusNode.canRequestFocus = widget._canRequestFocus!;
633 634
        }
        focusNode.descendantsAreFocusable = widget.descendantsAreFocusable;
635
        focusNode.descendantsAreTraversable = widget.descendantsAreTraversable;
636
      }
637
    } else {
638
      _focusAttachment!.detach();
639
      oldWidget.focusNode?.removeListener(_handleFocusChanged);
640
      _initNode();
641
    }
642

643 644 645
    if (oldWidget.autofocus != widget.autofocus) {
      _handleAutofocus();
    }
646 647 648
  }

  void _handleFocusChanged() {
649 650
    final bool hasPrimaryFocus = focusNode.hasPrimaryFocus;
    final bool canRequestFocus = focusNode.canRequestFocus;
651
    final bool descendantsAreFocusable = focusNode.descendantsAreFocusable;
652
    final bool descendantsAreTraversable = focusNode.descendantsAreTraversable;
653
    widget.onFocusChange?.call(focusNode.hasFocus);
654 655 656
    // Check the cached states that matter here, and call setState if they have
    // changed.
    if (_hadPrimaryFocus != hasPrimaryFocus) {
657
      setState(() {
658
        _hadPrimaryFocus = hasPrimaryFocus;
659 660
      });
    }
661
    if (_couldRequestFocus != canRequestFocus) {
662
      setState(() {
663
        _couldRequestFocus = canRequestFocus;
664 665
      });
    }
666
    if (_descendantsWereFocusable != descendantsAreFocusable) {
667
      setState(() {
668
        _descendantsWereFocusable = descendantsAreFocusable;
669 670
      });
    }
671 672 673 674 675
    if (_descendantsWereTraversable != descendantsAreTraversable) {
      setState(() {
        _descendantsWereTraversable = descendantsAreTraversable;
      });
    }
676 677 678 679
  }

  @override
  Widget build(BuildContext context) {
680
    _focusAttachment!.reparent(parent: widget.parentNode);
681 682 683
    Widget child = widget.child;
    if (widget.includeSemantics) {
      child = Semantics(
684 685
        focusable: _couldRequestFocus,
        focused: _hadPrimaryFocus,
686
        child: widget.child,
687 688
      );
    }
689
    return _FocusInheritedScope(
690 691
      node: focusNode,
      child: child,
692 693 694 695
    );
  }
}

696 697 698 699 700 701 702 703 704 705
/// A [FocusScope] is similar to a [Focus], but also serves as a scope for its
/// descendants, restricting focus traversal to the scoped controls.
///
/// For example a new [FocusScope] is created automatically when a route is
/// pushed, keeping the focus traversal from moving to a control in a previous
/// route.
///
/// If you just want to group widgets together in a group so that they are
/// traversed in a particular order, but the focus can still leave the group,
/// use a [FocusTraversalGroup].
706 707 708 709 710 711 712
///
/// Like [Focus], [FocusScope] provides an [onFocusChange] as a way to be
/// notified when the focus is given to or removed from this widget.
///
/// The [onKey] argument allows specification of a key event handler that is
/// invoked when this node or one of its children has focus. Keys are handed to
/// the primary focused widget first, and then they propagate through the
713 714 715
/// ancestors of that node, stopping if one of them returns
/// [KeyEventResult.handled] from [onKey], indicating that it has handled the
/// event.
716
///
717 718 719 720 721 722
/// Managing a [FocusScopeNode] means managing its lifecycle, listening for
/// changes in focus, and re-parenting it when needed to keep the focus
/// hierarchy in sync with the widget hierarchy. This widget does all of those
/// things for you. See [FocusScopeNode] for more information about the details
/// of what node management entails if you are not using a [FocusScope] widget
/// and you need to do it yourself.
723 724 725 726 727 728 729
///
/// [FocusScopeNode]s remember the last [FocusNode] that was focused within
/// their descendants, and can move that focus to the next/previous node, or a
/// node in a particular direction when the [FocusNode.nextFocus],
/// [FocusNode.previousFocus], or [FocusNode.focusInDirection] are called on a
/// [FocusNode] or [FocusScopeNode].
///
730 731 732 733 734
/// To move the focus, use methods on [FocusNode] by getting the [FocusNode]
/// through the [of] method. For instance, to move the focus to the next node in
/// the focus traversal order, call `Focus.of(context).nextFocus()`. To unfocus
/// a widget, call `Focus.of(context).unfocus()`.
///
735
/// {@tool dartpad}
736 737 738 739
/// This example demonstrates using a [FocusScope] to restrict focus to a particular
/// portion of the app. In this case, restricting focus to the visible part of a
/// Stack.
///
740
/// ** See code in examples/api/lib/widgets/focus_scope/focus_scope.0.dart **
741
/// {@end-tool}
742
///
743 744
/// See also:
///
745 746 747 748 749 750 751 752 753
///  * [FocusScopeNode], which represents a scope node in the focus hierarchy.
///  * [FocusNode], which represents a node in the focus hierarchy and has an
///    explanation of the focus system.
///  * [Focus], a widget that manages a [FocusNode] and allows easy access to
///    managing focus without having to manage the node.
///  * [FocusManager], a singleton that manages the focus and distributes key
///    events to focused nodes.
///  * [FocusTraversalPolicy], an object used to determine how to move the focus
///    to other nodes.
754 755
///  * [FocusTraversalGroup], a widget used to configure the focus traversal
///    policy for a widget subtree.
756 757 758 759 760
class FocusScope extends Focus {
  /// Creates a widget that manages a [FocusScopeNode].
  ///
  /// The [child] argument is required and must not be null.
  ///
761
  /// The [autofocus] argument must not be null.
762
  const FocusScope({
763
    super.key,
764
    FocusScopeNode? node,
765
    super.parentNode,
766 767 768 769 770 771 772 773
    required super.child,
    super.autofocus,
    super.onFocusChange,
    super.canRequestFocus,
    super.skipTraversal,
    super.onKeyEvent,
    super.onKey,
    super.debugLabel,
774 775 776 777 778 779
  })  : assert(child != null),
        assert(autofocus != null),
        super(
          focusNode: node,
        );

780 781 782 783 784 785 786
  /// Creates a FocusScope widget that uses the given [focusScopeNode] as the
  /// source of truth for attributes on the node, rather than the attributes of
  /// this widget.
  const factory FocusScope.withExternalFocusNode({
    Key? key,
    required Widget child,
    required FocusScopeNode focusScopeNode,
787
    FocusNode? parentNode,
788 789 790 791
    bool autofocus,
    ValueChanged<bool>? onFocusChange,
  })  = _FocusScopeWithExternalFocusNode;

792 793 794 795 796 797 798 799 800
  /// Returns the [FocusScopeNode] of the [FocusScope] that most tightly
  /// encloses the given [context].
  ///
  /// If this node doesn't have a [Focus] widget ancestor, then the
  /// [FocusManager.rootScope] is returned.
  ///
  /// The [context] argument must not be null.
  static FocusScopeNode of(BuildContext context) {
    assert(context != null);
801
    final _FocusInheritedScope? marker = context.dependOnInheritedWidgetOfExactType<_FocusInheritedScope>();
802
    return marker?.notifier?.nearestScope ?? context.owner!.focusManager.rootScope;
803 804 805
  }

  @override
806
  State<Focus> createState() => _FocusScopeState();
807 808
}

809 810 811 812
// Implements the behavior differences when the FocusScope.withExternalFocusNode
// constructor is used.
class _FocusScopeWithExternalFocusNode extends FocusScope {
  const _FocusScopeWithExternalFocusNode({
813 814
    super.key,
    required super.child,
815
    required FocusScopeNode focusScopeNode,
816
    super.parentNode,
817 818
    super.autofocus,
    super.onFocusChange,
819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835
  }) : super(
    node: focusScopeNode,
  );

  @override
  bool get _usingExternalFocus => true;
  @override
  FocusOnKeyEventCallback? get onKeyEvent => focusNode!.onKeyEvent;
  @override
  FocusOnKeyCallback? get onKey => focusNode!.onKey;
  @override
  bool get canRequestFocus => focusNode!.canRequestFocus;
  @override
  bool get skipTraversal => focusNode!.skipTraversal;
  @override
  bool get descendantsAreFocusable => focusNode!.descendantsAreFocusable;
  @override
836 837
  bool get descendantsAreTraversable => focusNode!.descendantsAreTraversable;
  @override
838 839 840
  String? get debugLabel => focusNode!.debugLabel;
}

841 842 843 844 845
class _FocusScopeState extends _FocusState {
  @override
  FocusScopeNode _createNode() {
    return FocusScopeNode(
      debugLabel: widget.debugLabel,
846 847
      canRequestFocus: widget.canRequestFocus,
      skipTraversal: widget.skipTraversal,
848 849 850 851 852
    );
  }

  @override
  Widget build(BuildContext context) {
853
    _focusAttachment!.reparent(parent: widget.parentNode);
854
    return Semantics(
855
      explicitChildNodes: true,
856
      child: _FocusInheritedScope(
857
        node: focusNode,
858
        child: widget.child,
859 860 861 862
      ),
    );
  }
}
863

864 865 866
// The InheritedWidget for Focus and FocusScope.
class _FocusInheritedScope extends InheritedNotifier<FocusNode> {
  const _FocusInheritedScope({
867
    required FocusNode node,
868
    required super.child,
869 870
  })  : assert(node != null),
        assert(child != null),
871
        super(notifier: node);
872
}
873 874 875 876

/// A widget that controls whether or not the descendants of this widget are
/// focusable.
///
877
/// Does not affect the value of [Focus.canRequestFocus] on the descendants.
878 879 880 881 882 883 884 885 886 887 888 889 890 891
///
/// See also:
///
///  * [Focus], a widget for adding and managing a [FocusNode] in the widget tree.
///  * [FocusTraversalGroup], a widget that groups widgets for focus traversal,
///    and can also be used in the same way as this widget by setting its
///    `descendantsAreFocusable` attribute.
class ExcludeFocus extends StatelessWidget {
  /// Const constructor for [ExcludeFocus] widget.
  ///
  /// The [excluding] argument must not be null.
  ///
  /// The [child] argument is required, and must not be null.
  const ExcludeFocus({
892
    super.key,
893
    this.excluding = true,
894
    required this.child,
895
  })  : assert(excluding != null),
896
        assert(child != null);
897 898 899 900 901 902

  /// If true, will make this widget's descendants unfocusable.
  ///
  /// Defaults to true.
  ///
  /// If any descendants are focused when this is set to true, they will be
903
  /// unfocused. When [excluding] is set to false again, they will not be
904 905
  /// refocused, although they will be able to accept focus again.
  ///
906 907
  /// Does not affect the value of [FocusNode.canRequestFocus] on the
  /// descendants.
908 909 910
  ///
  /// See also:
  ///
911 912 913 914 915 916
  /// * [Focus.descendantsAreFocusable], the attribute of a [Focus] widget that
  ///   controls this same property for focus widgets.
  /// * [FocusTraversalGroup], a widget used to group together and configure the
  ///   focus traversal policy for a widget subtree that has a
  ///   `descendantsAreFocusable` parameter to conditionally block focus for a
  ///   subtree.
917 918 919 920
  final bool excluding;

  /// The child widget of this [ExcludeFocus].
  ///
921
  /// {@macro flutter.widgets.ProxyWidget.child}
922 923 924 925 926 927 928
  final Widget child;

  @override
  Widget build(BuildContext context) {
    return Focus(
      canRequestFocus: false,
      skipTraversal: true,
929
      includeSemantics: false,
930 931 932 933 934
      descendantsAreFocusable: !excluding,
      child: child,
    );
  }
}