focus_scope.dart 37.8 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
/// When the focus is gained or lost, [onFocusChange] is called.
16
///
17 18
/// For keyboard events, [onKey] is called if [FocusNode.hasFocus] is true for
/// this widget's [focusNode], unless a focused descendant's [onKey] callback
19
/// returns true when called.
Adam Barth's avatar
Adam Barth committed
20
///
21
/// This widget does not provide any visual indication that the focus has
22
/// changed. Any desired visual changes should be made when [onFocusChange] is
23 24 25 26 27 28 29
/// 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
30
/// [FocusNode.hasFocus] from a build method, which also establishes a relationship
31 32 33 34 35
/// between the calling widget and the [Focus] widget that will rebuild the
/// calling widget when the focus changes.
///
/// Managing a [FocusNode] means managing its lifecycle, listening for changes
/// in focus, and re-parenting it when needed to keep the focus hierarchy in
36 37 38 39 40 41 42 43 44
/// 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.
///
/// 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].
45
///
46 47 48 49
/// 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()`.
50
///
51
/// {@tool dartpad --template=stateful_widget_scaffold}
52 53 54 55 56 57
/// 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].
///
/// ```dart imports
/// import 'package:flutter/services.dart';
58
/// ```
59
///
60 61 62
/// ```dart
/// Color _color = Colors.white;
///
63
/// KeyEventResult _handleKeyPress(FocusNode node, RawKeyEvent event) {
64 65 66 67 68 69 70
///   if (event is RawKeyDownEvent) {
///     print('Focus node ${node.debugLabel} got key event: ${event.logicalKey}');
///     if (event.logicalKey == LogicalKeyboardKey.keyR) {
///       print('Changing color to red.');
///       setState(() {
///         _color = Colors.red;
///       });
71
///       return KeyEventResult.handled;
72 73 74 75 76
///     } else if (event.logicalKey == LogicalKeyboardKey.keyG) {
///       print('Changing color to green.');
///       setState(() {
///         _color = Colors.green;
///       });
77
///       return KeyEventResult.handled;
78 79 80 81 82
///     } else if (event.logicalKey == LogicalKeyboardKey.keyB) {
///       print('Changing color to blue.');
///       setState(() {
///         _color = Colors.blue;
///       });
83
///       return KeyEventResult.handled;
84 85
///     }
///   }
86
///   return KeyEventResult.ignored;
87 88 89 90 91 92 93 94 95
/// }
///
/// @override
/// Widget build(BuildContext context) {
///   final TextTheme textTheme = Theme.of(context).textTheme;
///   return FocusScope(
///     debugLabel: 'Scope',
///     autofocus: true,
///     child: DefaultTextStyle(
96
///       style: textTheme.headline4!,
97 98 99 100 101 102 103 104 105 106
///       child: Focus(
///         onKey: _handleKeyPress,
///         debugLabel: 'Button',
///         child: Builder(
///           builder: (BuildContext context) {
///             final FocusNode focusNode = Focus.of(context);
///             final bool hasFocus = focusNode.hasFocus;
///             return GestureDetector(
///               onTap: () {
///                 if (hasFocus) {
107
///                   focusNode.unfocus();
108
///                 } else {
109
///                   focusNode.requestFocus();
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
///                 }
///               },
///               child: Center(
///                 child: Container(
///                   width: 400,
///                   height: 100,
///                   alignment: Alignment.center,
///                   color: hasFocus ? _color : Colors.white,
///                   child: Text(hasFocus ? "I'm in color! Press R,G,B!" : 'Press to focus'),
///                 ),
///               ),
///             );
///           },
///         ),
///       ),
///     ),
///   );
/// }
/// ```
/// {@end-tool}
Adam Barth's avatar
Adam Barth committed
130
///
131
/// {@tool dartpad --template=stateless_widget_material}
132 133 134 135 136 137 138 139 140 141
/// 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.
///
/// ```dart preamble
/// class FocusableText extends StatelessWidget {
142 143 144 145
///   const FocusableText(this.data, {
///     Key? key,
///     required this.autofocus,
///   }) : super(key: key);
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
///
///   /// The string to display as the text for this widget.
///   final String data;
///
///   /// Whether or not to focus this widget initially if nothing else is focused.
///   final bool autofocus;
///
///   @override
///   Widget build(BuildContext context) {
///     return Focus(
///       autofocus: autofocus,
///       child: Builder(builder: (BuildContext context) {
///         // The contents of this Builder are being made focusable. It is inside
///         // of a Builder because the builder provides the correct context
///         // variable for Focus.of() to be able to find the Focus widget that is
///         // the Builder's parent. Without the builder, the context variable used
///         // would be the one given the FocusableText build function, and that
///         // would start looking for a Focus widget ancestor of the FocusableText
///         // instead of finding the one inside of its build function.
///         return Container(
///           padding: EdgeInsets.all(8.0),
///           // Change the color based on whether or not this Container has focus.
///           color: Focus.of(context).hasPrimaryFocus ? Colors.black12 : null,
///           child: Text(data),
///         );
///       }),
///     );
///   }
/// }
/// ```
///
/// ```dart
/// Widget build(BuildContext context) {
///   return Scaffold(
///     body: ListView.builder(
///       itemBuilder: (context, index) => FocusableText(
///         'Item $index',
///         autofocus: index == 0,
///       ),
///       itemCount: 50,
///     ),
///   );
/// }
/// ```
/// {@end-tool}
///
192
/// {@tool dartpad --template=stateful_widget_material}
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
/// 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.
///
/// ```dart
/// int focusedChild = 0;
/// List<Widget> children = <Widget>[];
/// List<FocusNode> childFocusNodes = <FocusNode>[];
///
/// @override
/// void initState() {
///   super.initState();
///   // Add the first child.
///   _addChild();
/// }
///
/// @override
/// void dispose() {
///   super.dispose();
///   childFocusNodes.forEach((FocusNode node) => node.dispose());
/// }
///
/// void _addChild() {
///   // Calling requestFocus here creates a deferred request for focus, since the
///   // node is not yet part of the focus tree.
///   childFocusNodes
///       .add(FocusNode(debugLabel: 'Child ${children.length}')..requestFocus());
///
///   children.add(Padding(
///     padding: const EdgeInsets.all(2.0),
///     child: ActionChip(
///       focusNode: childFocusNodes.last,
///       label: Text('CHILD ${children.length}'),
///       onPressed: () {},
///     ),
///   ));
/// }
///
/// @override
/// Widget build(BuildContext context) {
///   return Scaffold(
///     body: Center(
///       child: Wrap(
///         children: children,
///       ),
///     ),
///     floatingActionButton: FloatingActionButton(
///       onPressed: () {
///         setState(() {
///           focusedChild = children.length;
///           _addChild();
///         });
///       },
///       child: Icon(Icons.add),
///     ),
///   );
/// }
/// ```
/// {@end-tool}
///
256
/// See also:
Adam Barth's avatar
Adam Barth committed
257
///
258 259 260 261 262 263 264 265 266 267 268
///  * [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.
269 270
///  * [FocusTraversalGroup], a widget that groups together and imposes a
///    traversal policy on the [Focus] nodes below it in the widget hierarchy.
271 272
class Focus extends StatefulWidget {
  /// Creates a widget that manages a [FocusNode].
273
  ///
274 275
  /// The [child] argument is required and must not be null.
  ///
276
  /// The [autofocus] argument must not be null.
277
  const Focus({
278 279
    Key? key,
    required this.child,
280
    this.focusNode,
281
    this.autofocus = false,
282 283 284
    this.onFocusChange,
    this.onKey,
    this.debugLabel,
285
    this.canRequestFocus,
286
    this.descendantsAreFocusable = true,
287
    this.skipTraversal,
288
    this.includeSemantics = true,
289 290
  })  : assert(child != null),
        assert(autofocus != null),
291
        assert(descendantsAreFocusable != null),
292
        assert(includeSemantics != null),
293
        super(key: key);
294

295 296 297 298 299 300 301 302 303 304
  /// A debug label for this widget.
  ///
  /// Not used for anything except to be printed in the diagnostic output from
  /// [toString] or [toStringDeep]. Also unused if a [focusNode] is provided,
  /// since that node can have its own [FocusNode.debugLabel].
  ///
  /// To get a string with the entire tree, call [debugDescribeFocusTree]. To
  /// print it to the console call [debugDumpFocusTree].
  ///
  /// Defaults to null.
305
  final String? debugLabel;
306

307
  /// The child widget of this [Focus].
308
  ///
309
  /// {@macro flutter.widgets.ProxyWidget.child}
310
  final Widget child;
311

312 313
  /// Handler for keys pressed when this object or one of its children has
  /// focus.
314
  ///
315 316 317 318 319 320 321 322 323 324
  /// Key events are first given to the [FocusNode] that has primary focus, and
  /// 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.
325
  final FocusOnKeyCallback? onKey;
326 327 328

  /// Handler called when the focus changes.
  ///
329
  /// Called with true if this widget's node gains focus, and false if it loses
330
  /// focus.
331
  final ValueChanged<bool>? onFocusChange;
332

333
  /// {@template flutter.widgets.Focus.autofocus}
334 335 336
  /// True if this widget will be selected as the initial focus when no other
  /// node in its scope is currently focused.
  ///
337 338 339 340 341 342
  /// 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}
343 344
  final bool autofocus;

345 346
  /// {@template flutter.widgets.Focus.focusNode}
  /// An optional focus node to use as the focus node for this widget.
347
  ///
348 349 350 351 352
  /// 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
  /// [focusNode] is not supplied. If supplied, the given `focusNode` will be
  /// _hosted_ by this widget, but not owned. See [FocusNode] for more
  /// information on what being hosted and/or owned implies.
353 354 355 356
  ///
  /// 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
357 358 359
  /// done with it, but this widget will attach/detach and reparent the node
  /// when needed.
  /// {@endtemplate}
360
  final FocusNode? focusNode;
361

362 363 364
  /// Sets the [FocusNode.skipTraversal] flag on the focus node so that it won't
  /// be visited by the [FocusTraversalPolicy].
  ///
365
  /// This is sometimes useful if a [Focus] widget should receive key events as
366
  /// part of the focus chain, but shouldn't be accessible via focus traversal.
367
  ///
368 369 370
  /// 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.
371
  final bool? skipTraversal;
372

373 374
  /// {@template flutter.widgets.Focus.includeSemantics}
  /// Include semantics information in this widget.
375
  ///
376 377 378
  /// If true, this widget will include a [Semantics] node that indicates the
  /// [SemanticsProperties.focusable] and [SemanticsProperties.focused]
  /// properties.
379
  ///
380
  /// It is not typical to set this to false, as that can affect the semantics
381 382 383
  /// information available to accessibility systems.
  ///
  /// Must not be null, defaults to true.
384
  /// {@endtemplate}
385 386
  final bool includeSemantics;

387
  /// {@template flutter.widgets.Focus.canRequestFocus}
388 389 390
  /// If true, this widget may request the primary focus.
  ///
  /// Defaults to true.  Set to false if you want the [FocusNode] this widget
391 392 393
  /// 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.
394
  ///
395 396
  /// This is different than [Focus.skipTraversal] because [Focus.skipTraversal]
  /// still allows the widget to be focused, just not traversed to.
397
  ///
398 399
  /// Setting [FocusNode.canRequestFocus] to false implies that the widget will
  /// also be skipped for traversal purposes.
400 401 402
  ///
  /// See also:
  ///
403 404 405 406
  /// * [FocusTraversalGroup], a widget that sets the traversal policy for its
  ///   descendants.
  /// * [FocusTraversalPolicy], a class that can be extended to describe a
  ///   traversal policy.
407
  /// {@endtemplate}
408
  final bool? canRequestFocus;
409

410 411 412 413
  /// {@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
414
  /// descendants): for that, use [FocusNode.canRequestFocus].
415 416 417 418 419
  ///
  /// 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.
  ///
420 421
  /// Does not affect the value of [FocusNode.canRequestFocus] on the
  /// descendants.
422 423 424
  ///
  /// See also:
  ///
425 426 427 428 429 430
  /// * [ExcludeFocus], a widget that uses this property to conditionally
  ///   exclude 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.
431 432 433
  /// {@endtemplate}
  final bool descendantsAreFocusable;

434 435
  /// Returns the [focusNode] of the [Focus] that most tightly encloses the
  /// given [BuildContext].
436
  ///
437 438
  /// If no [Focus] node is found before reaching the nearest [FocusScope]
  /// widget, or there is no [Focus] widget in scope, then this method will
439
  /// throw an exception.
440
  ///
441
  /// The `context` and `scopeOk` arguments must not be null.
442 443 444
  ///
  /// Calling this function creates a dependency that will rebuild the given
  /// context when the focus changes.
445 446 447 448 449 450
  ///
  /// 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 }) {
451
    assert(context != null);
452
    assert(scopeOk != null);
453 454
    final _FocusMarker? marker = context.dependOnInheritedWidgetOfExactType<_FocusMarker>();
    final FocusNode? node = marker?.notifier;
455 456
    assert(() {
      if (node == null) {
457
        throw FlutterError(
458 459 460 461 462 463
          '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'
          '  $context'
464 465
        );
      }
466 467 468 469
      return true;
    }());
    assert(() {
      if (!scopeOk && node is FocusScopeNode) {
470
        throw FlutterError(
471 472 473 474 475 476 477 478
          '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'
          '  $context'
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
      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);
    final _FocusMarker? marker = context.dependOnInheritedWidgetOfExactType<_FocusMarker>();
    final FocusNode? node = marker?.notifier;
    if (node == null) {
      return null;
    }
    if (!scopeOk && node is FocusScopeNode) {
511 512 513
      return null;
    }
    return node;
514 515
  }

516 517 518
  /// Returns true if the nearest enclosing [Focus] widget's node is focused.
  ///
  /// A convenience method to allow build methods to write:
519 520 521 522 523 524
  /// `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.
525 526 527
  ///
  /// Calling this function creates a dependency that will rebuild the given
  /// context when the focus changes.
528
  static bool isAt(BuildContext context) => Focus.maybeOf(context)?.hasFocus ?? false;
529

530
  @override
531 532 533 534
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
    properties.add(StringProperty('debugLabel', debugLabel, defaultValue: null));
    properties.add(FlagProperty('autofocus', value: autofocus, ifTrue: 'AUTOFOCUS', defaultValue: false));
535 536 537
    properties.add(FlagProperty('canRequestFocus', value: canRequestFocus, ifFalse: 'NOT FOCUSABLE', defaultValue: false));
    properties.add(FlagProperty('descendantsAreFocusable', value: descendantsAreFocusable, ifFalse: 'DESCENDANTS UNFOCUSABLE', defaultValue: true));
    properties.add(DiagnosticsProperty<FocusNode>('focusNode', focusNode, defaultValue: null));
538 539 540 541
  }

  @override
  _FocusState createState() => _FocusState();
542 543
}

544
class _FocusState extends State<Focus> {
545 546 547 548 549
  FocusNode? _internalNode;
  FocusNode get focusNode => widget.focusNode ?? _internalNode!;
  bool? _hasPrimaryFocus;
  bool? _canRequestFocus;
  bool? _descendantsAreFocusable;
550
  bool _didAutofocus = false;
551
  FocusAttachment? _focusAttachment;
552 553 554 555 556 557 558 559 560 561

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

  void _initNode() {
    if (widget.focusNode == null) {
      // Only create a new node if the widget doesn't have one.
562 563
      // This calls a function instead of just allocating in place because
      // _createNode is overridden in _FocusScopeState.
564 565
      _internalNode ??= _createNode();
    }
566
    focusNode.descendantsAreFocusable = widget.descendantsAreFocusable;
567
    if (widget.skipTraversal != null) {
568
      focusNode.skipTraversal = widget.skipTraversal!;
569 570
    }
    if (widget.canRequestFocus != null) {
571
      focusNode.canRequestFocus = widget.canRequestFocus!;
572
    }
573
    _canRequestFocus = focusNode.canRequestFocus;
574
    _descendantsAreFocusable = focusNode.descendantsAreFocusable;
575
    _hasPrimaryFocus = focusNode.hasPrimaryFocus;
576
    _focusAttachment = focusNode.attach(context, onKey: widget.onKey);
577

578
    // Add listener even if the _internalNode existed before, since it should
579
    // not be listening now if we're re-using a previous one because it should
580
    // have already removed its listener.
581
    focusNode.addListener(_handleFocusChanged);
582 583
  }

584 585 586 587
  FocusNode _createNode() {
    return FocusNode(
      debugLabel: widget.debugLabel,
      canRequestFocus: widget.canRequestFocus ?? true,
588
      descendantsAreFocusable: widget.descendantsAreFocusable,
589 590 591
      skipTraversal: widget.skipTraversal ?? false,
    );
  }
592 593 594 595 596

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

600 601 602 603 604
    // Don't manage the lifetime of external nodes given to the widget, just the
    // internal node.
    _internalNode?.dispose();
    super.dispose();
  }
605 606 607 608

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
609
    _focusAttachment?.reparent();
610 611 612 613
    _handleAutofocus();
  }

  void _handleAutofocus() {
614
    if (!_didAutofocus && widget.autofocus) {
615
      FocusScope.of(context).autofocus(focusNode);
616 617 618 619 620
      _didAutofocus = true;
    }
  }

  @override
621 622
  void deactivate() {
    super.deactivate();
623 624 625 626 627 628 629
    // 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();
630 631 632 633 634 635
    _didAutofocus = false;
  }

  @override
  void didUpdateWidget(Focus oldWidget) {
    super.didUpdateWidget(oldWidget);
636 637 638 639
    assert(() {
      // Only update the debug label in debug builds, and only if we own the
      // node.
      if (oldWidget.debugLabel != widget.debugLabel && _internalNode != null) {
640
        _internalNode!.debugLabel = widget.debugLabel;
641 642 643 644 645
      }
      return true;
    }());

    if (oldWidget.focusNode == widget.focusNode) {
646 647 648
      if (widget.onKey != focusNode.onKey) {
        focusNode.onKey = widget.onKey;
      }
649
      if (widget.skipTraversal != null) {
650
        focusNode.skipTraversal = widget.skipTraversal!;
651 652
      }
      if (widget.canRequestFocus != null) {
653
        focusNode.canRequestFocus = widget.canRequestFocus!;
654
      }
655
      focusNode.descendantsAreFocusable = widget.descendantsAreFocusable;
656
    } else {
657
      _focusAttachment!.detach();
658 659
      focusNode.removeListener(_handleFocusChanged);
      _initNode();
660
    }
661

662 663 664
    if (oldWidget.autofocus != widget.autofocus) {
      _handleAutofocus();
    }
665 666 667
  }

  void _handleFocusChanged() {
668 669
    final bool hasPrimaryFocus = focusNode.hasPrimaryFocus;
    final bool canRequestFocus = focusNode.canRequestFocus;
670
    final bool descendantsAreFocusable = focusNode.descendantsAreFocusable;
671
    if (widget.onFocusChange != null) {
672
      widget.onFocusChange!(focusNode.hasFocus);
673
    }
674
    if (_hasPrimaryFocus != hasPrimaryFocus) {
675
      setState(() {
676
        _hasPrimaryFocus = hasPrimaryFocus;
677 678
      });
    }
679
    if (_canRequestFocus != canRequestFocus) {
680
      setState(() {
681
        _canRequestFocus = canRequestFocus;
682 683
      });
    }
684 685 686 687 688
    if (_descendantsAreFocusable != descendantsAreFocusable) {
      setState(() {
        _descendantsAreFocusable = descendantsAreFocusable;
      });
    }
689 690 691 692
  }

  @override
  Widget build(BuildContext context) {
693
    _focusAttachment!.reparent();
694 695 696
    Widget child = widget.child;
    if (widget.includeSemantics) {
      child = Semantics(
697 698
        focusable: _canRequestFocus,
        focused: _hasPrimaryFocus,
699
        child: widget.child,
700 701 702 703 704
      );
    }
    return _FocusMarker(
      node: focusNode,
      child: child,
705 706 707 708
    );
  }
}

709 710 711 712 713 714 715 716 717 718
/// 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].
719 720 721 722 723 724 725 726 727 728
///
/// 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
/// ancestors of that node, stopping if one of them returns true from [onKey],
/// indicating that it has handled the event.
///
729 730 731 732 733 734
/// 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.
735 736 737 738 739 740 741
///
/// [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].
///
742 743 744 745 746
/// 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()`.
///
747
/// {@tool dartpad --template=stateful_widget_material}
748 749 750 751 752 753 754 755 756 757
/// 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.
///
/// ```dart preamble
/// /// A demonstration pane.
/// ///
/// /// This is just a separate widget to simplify the example.
/// class Pane extends StatelessWidget {
///   const Pane({
758 759
///     Key? key,
///     required this.focusNode,
760
///     this.onPressed,
761 762
///     required this.backgroundColor,
///     required this.icon,
763 764 765 766
///     this.child,
///   }) : super(key: key);
///
///   final FocusNode focusNode;
767
///   final VoidCallback? onPressed;
768 769
///   final Color backgroundColor;
///   final Widget icon;
770
///   final Widget? child;
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
///
///   @override
///   Widget build(BuildContext context) {
///     return Material(
///       color: backgroundColor,
///       child: Stack(
///         fit: StackFit.expand,
///         children: <Widget>[
///           Center(
///             child: child,
///           ),
///           Align(
///             alignment: Alignment.topLeft,
///             child: IconButton(
///               autofocus: true,
///               focusNode: focusNode,
///               onPressed: onPressed,
///               icon: icon,
///             ),
///           ),
///         ],
///       ),
///     );
///   }
/// }
/// ```
///
/// ```dart
///   bool backdropIsVisible = false;
///   FocusNode backdropNode = FocusNode(debugLabel: 'Close Backdrop Button');
///   FocusNode foregroundNode = FocusNode(debugLabel: 'Option Button');
///
///   @override
///   void dispose() {
///     super.dispose();
///     backdropNode.dispose();
///     foregroundNode.dispose();
///   }
///
///   Widget _buildStack(BuildContext context, BoxConstraints constraints) {
///     Size stackSize = constraints.biggest;
///     return Stack(
///       fit: StackFit.expand,
///       // The backdrop is behind the front widget in the Stack, but the widgets
///       // would still be active and traversable without the FocusScope.
///       children: <Widget>[
///         // TRY THIS: Try removing this FocusScope entirely to see how it affects
///         // the behavior. Without this FocusScope, the "ANOTHER BUTTON TO FOCUS"
///         // button, and the IconButton in the backdrop Pane would be focusable
///         // even when the backdrop wasn't visible.
///         FocusScope(
///           // TRY THIS: Try commenting out this line. Notice that the focus
///           // starts on the backdrop and is stuck there? It seems like the app is
///           // non-responsive, but it actually isn't. This line makes sure that
///           // this focus scope and its children can't be focused when they're not
///           // visible. It might help to make the background color of the
///           // foreground pane semi-transparent to see it clearly.
///           canRequestFocus: backdropIsVisible,
///           child: Pane(
///             icon: Icon(Icons.close),
///             focusNode: backdropNode,
///             backgroundColor: Colors.lightBlue,
///             onPressed: () => setState(() => backdropIsVisible = false),
///             child: Column(
///               mainAxisAlignment: MainAxisAlignment.center,
///               children: <Widget>[
///                 // This button would be not visible, but still focusable from
///                 // the foreground pane without the FocusScope.
839
///                 ElevatedButton(
840 841 842 843
///                   onPressed: () => print('You pressed the other button!'),
///                   child: Text('ANOTHER BUTTON TO FOCUS'),
///                 ),
///                 DefaultTextStyle(
844
///                     style: Theme.of(context).textTheme.headline2!,
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
///                     child: Text('BACKDROP')),
///               ],
///             ),
///           ),
///         ),
///         AnimatedPositioned(
///           curve: Curves.easeInOut,
///           duration: const Duration(milliseconds: 300),
///           top: backdropIsVisible ? stackSize.height * 0.9 : 0.0,
///           width: stackSize.width,
///           height: stackSize.height,
///           onEnd: () {
///             if (backdropIsVisible) {
///               backdropNode.requestFocus();
///             } else {
///               foregroundNode.requestFocus();
///             }
///           },
///           child: Pane(
///             icon: Icon(Icons.menu),
///             focusNode: foregroundNode,
///             // TRY THIS: Try changing this to Colors.green.withOpacity(0.8) to see for
///             // yourself that the hidden components do/don't get focus.
///             backgroundColor: Colors.green,
///             onPressed: backdropIsVisible
///                 ? null
///                 : () => setState(() => backdropIsVisible = true),
///             child: DefaultTextStyle(
873
///                 style: Theme.of(context).textTheme.headline2!,
874 875 876 877 878 879 880 881 882 883 884 885 886 887 888
///                 child: Text('FOREGROUND')),
///           ),
///         ),
///       ],
///     );
///   }
///
///   @override
///   Widget build(BuildContext context) {
///     // Use a LayoutBuilder so that we can base the size of the stack on the size
///     // of its parent.
///     return LayoutBuilder(builder: _buildStack);
///   }
/// ```
/// {@end-tool}
889
///
890 891
/// See also:
///
892 893 894 895 896 897 898 899 900
///  * [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.
901 902
///  * [FocusTraversalGroup], a widget used to configure the focus traversal
///    policy for a widget subtree.
903 904 905 906 907
class FocusScope extends Focus {
  /// Creates a widget that manages a [FocusScopeNode].
  ///
  /// The [child] argument is required and must not be null.
  ///
908
  /// The [autofocus] argument must not be null.
909
  const FocusScope({
910 911 912
    Key? key,
    FocusScopeNode? node,
    required Widget child,
913
    bool autofocus = false,
914 915 916 917 918
    ValueChanged<bool>? onFocusChange,
    bool? canRequestFocus,
    bool? skipTraversal,
    FocusOnKeyCallback? onKey,
    String? debugLabel,
919 920 921 922 923 924 925 926
  })  : assert(child != null),
        assert(autofocus != null),
        super(
          key: key,
          child: child,
          focusNode: node,
          autofocus: autofocus,
          onFocusChange: onFocusChange,
927 928
          canRequestFocus: canRequestFocus,
          skipTraversal: skipTraversal,
929 930 931 932 933 934 935 936 937 938 939 940 941
          onKey: onKey,
          debugLabel: debugLabel,
        );

  /// 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);
942 943
    final _FocusMarker? marker = context.dependOnInheritedWidgetOfExactType<_FocusMarker>();
    return marker?.notifier?.nearestScope ?? context.owner!.focusManager.rootScope;
944 945 946 947 948 949 950 951 952 953 954
  }

  @override
  _FocusScopeState createState() => _FocusScopeState();
}

class _FocusScopeState extends _FocusState {
  @override
  FocusScopeNode _createNode() {
    return FocusScopeNode(
      debugLabel: widget.debugLabel,
955 956
      canRequestFocus: widget.canRequestFocus ?? true,
      skipTraversal: widget.skipTraversal ?? false,
957 958 959 960 961
    );
  }

  @override
  Widget build(BuildContext context) {
962
    _focusAttachment!.reparent();
963
    return Semantics(
964
      explicitChildNodes: true,
965
      child: _FocusMarker(
966
        node: focusNode,
967
        child: widget.child,
968 969 970 971
      ),
    );
  }
}
972 973 974 975

// The InheritedWidget marker for Focus and FocusScope.
class _FocusMarker extends InheritedNotifier<FocusNode> {
  const _FocusMarker({
976 977 978
    Key? key,
    required FocusNode node,
    required Widget child,
979 980 981 982
  })  : assert(node != null),
        assert(child != null),
        super(key: key, notifier: node, child: child);
}
983 984 985 986

/// A widget that controls whether or not the descendants of this widget are
/// focusable.
///
987
/// Does not affect the value of [Focus.canRequestFocus] on the descendants.
988 989 990 991 992 993 994 995 996 997 998 999 1000 1001
///
/// 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({
1002
    Key? key,
1003
    this.excluding = true,
1004
    required this.child,
1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016
  })  : assert(excluding != null),
        assert(child != null),
        super(key: key);

  /// 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
  /// unfocused. When `excluding` is set to false again, they will not be
  /// refocused, although they will be able to accept focus again.
  ///
1017 1018
  /// Does not affect the value of [FocusNode.canRequestFocus] on the
  /// descendants.
1019 1020 1021
  ///
  /// See also:
  ///
1022 1023 1024 1025 1026 1027
  /// * [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.
1028 1029 1030 1031
  final bool excluding;

  /// The child widget of this [ExcludeFocus].
  ///
1032
  /// {@macro flutter.widgets.ProxyWidget.child}
1033 1034 1035 1036 1037 1038 1039
  final Widget child;

  @override
  Widget build(BuildContext context) {
    return Focus(
      canRequestFocus: false,
      skipTraversal: true,
1040
      includeSemantics: false,
1041 1042 1043 1044 1045
      descendantsAreFocusable: !excluding,
      child: child,
    );
  }
}