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

5
import 'package:flutter/semantics.dart';
6 7 8
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
9

10 11
import 'semantics_tester.dart';

12
void main() {
13
  group('FocusScope', () {
14 15
    testWidgets('Can focus', (WidgetTester tester) async {
      final GlobalKey<TestFocusState> key = GlobalKey();
16

17
      await tester.pumpWidget(
18
        TestFocus(key: key),
19
      );
20

21
      expect(key.currentState!.focusNode.hasFocus, isFalse);
22

23
      FocusScope.of(key.currentContext!).requestFocus(key.currentState!.focusNode);
24
      await tester.pumpAndSettle();
25

26
      expect(key.currentState!.focusNode.hasFocus, isTrue);
27 28
      expect(find.text('A FOCUSED'), findsOneWidget);
    });
29

30 31 32 33 34
    testWidgets('Can unfocus', (WidgetTester tester) async {
      final GlobalKey<TestFocusState> keyA = GlobalKey();
      final GlobalKey<TestFocusState> keyB = GlobalKey();
      await tester.pumpWidget(
        Column(
35
          children: <Widget>[
36
            TestFocus(key: keyA),
37
            TestFocus(key: keyB, name: 'b'),
38
          ],
39
        ),
40
      );
41

42
      expect(keyA.currentState!.focusNode.hasFocus, isFalse);
43
      expect(find.text('a'), findsOneWidget);
44
      expect(keyB.currentState!.focusNode.hasFocus, isFalse);
45
      expect(find.text('b'), findsOneWidget);
46

47
      FocusScope.of(keyA.currentContext!).requestFocus(keyA.currentState!.focusNode);
48
      await tester.pumpAndSettle();
49

50
      expect(keyA.currentState!.focusNode.hasFocus, isTrue);
51
      expect(find.text('A FOCUSED'), findsOneWidget);
52
      expect(keyB.currentState!.focusNode.hasFocus, isFalse);
53
      expect(find.text('b'), findsOneWidget);
54

55
      // Set focus to the "B" node to unfocus the "A" node.
56
      FocusScope.of(keyB.currentContext!).requestFocus(keyB.currentState!.focusNode);
57
      await tester.pumpAndSettle();
58

59
      expect(keyA.currentState!.focusNode.hasFocus, isFalse);
60
      expect(find.text('a'), findsOneWidget);
61
      expect(keyB.currentState!.focusNode.hasFocus, isTrue);
62 63
      expect(find.text('B FOCUSED'), findsOneWidget);
    });
64

65 66 67 68 69 70
    testWidgets('Autofocus works', (WidgetTester tester) async {
      final GlobalKey<TestFocusState> keyA = GlobalKey();
      final GlobalKey<TestFocusState> keyB = GlobalKey();
      await tester.pumpWidget(
        Column(
          children: <Widget>[
71
            TestFocus(key: keyA),
72 73 74 75 76 77 78
            TestFocus(key: keyB, name: 'b', autofocus: true),
          ],
        ),
      );

      await tester.pump();

79
      expect(keyA.currentState!.focusNode.hasFocus, isFalse);
80
      expect(find.text('a'), findsOneWidget);
81
      expect(keyB.currentState!.focusNode.hasFocus, isTrue);
82 83 84
      expect(find.text('B FOCUSED'), findsOneWidget);
    });

85 86 87 88 89 90
    testWidgets('Can have multiple focused children and they update accordingly', (WidgetTester tester) async {
      final GlobalKey<TestFocusState> keyA = GlobalKey();
      final GlobalKey<TestFocusState> keyB = GlobalKey();

      await tester.pumpWidget(
        Column(
91
          children: <Widget>[
92 93 94 95 96 97 98
            TestFocus(
              key: keyA,
              autofocus: true,
            ),
            TestFocus(
              key: keyB,
              name: 'b',
99 100 101
            ),
          ],
        ),
102 103 104 105
      );

      // Autofocus is delayed one frame.
      await tester.pump();
106
      expect(keyA.currentState!.focusNode.hasFocus, isTrue);
107
      expect(find.text('A FOCUSED'), findsOneWidget);
108
      expect(keyB.currentState!.focusNode.hasFocus, isFalse);
109 110 111
      expect(find.text('b'), findsOneWidget);
      await tester.tap(find.text('A FOCUSED'));
      await tester.pump();
112
      expect(keyA.currentState!.focusNode.hasFocus, isTrue);
113
      expect(find.text('A FOCUSED'), findsOneWidget);
114
      expect(keyB.currentState!.focusNode.hasFocus, isFalse);
115 116 117
      expect(find.text('b'), findsOneWidget);
      await tester.tap(find.text('b'));
      await tester.pump();
118
      expect(keyA.currentState!.focusNode.hasFocus, isFalse);
119
      expect(find.text('a'), findsOneWidget);
120
      expect(keyB.currentState!.focusNode.hasFocus, isTrue);
121 122 123
      expect(find.text('B FOCUSED'), findsOneWidget);
      await tester.tap(find.text('a'));
      await tester.pump();
124
      expect(keyA.currentState!.focusNode.hasFocus, isTrue);
125
      expect(find.text('A FOCUSED'), findsOneWidget);
126
      expect(keyB.currentState!.focusNode.hasFocus, isFalse);
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
      expect(find.text('b'), findsOneWidget);
    });

    // This moves a focus node first into a focus scope that is added to its
    // parent, and then out of that focus scope again.
    testWidgets('Can move focus in and out of FocusScope', (WidgetTester tester) async {
      final FocusScopeNode parentFocusScope = FocusScopeNode(debugLabel: 'Parent Scope Node');
      final FocusScopeNode childFocusScope = FocusScopeNode(debugLabel: 'Child Scope Node');
      final GlobalKey<TestFocusState> key = GlobalKey();

      // Initially create the focus inside of the parent FocusScope.
      await tester.pumpWidget(
        FocusScope(
          debugLabel: 'Parent Scope',
          node: parentFocusScope,
          autofocus: true,
          child: Column(
            children: <Widget>[
              TestFocus(
                key: key,
                debugLabel: 'Child',
              ),
            ],
          ),
        ),
      );

154
      expect(key.currentState!.focusNode.hasFocus, isFalse);
155
      expect(find.text('a'), findsOneWidget);
156
      FocusScope.of(key.currentContext!).requestFocus(key.currentState!.focusNode);
157 158
      await tester.pumpAndSettle();

159
      expect(key.currentState!.focusNode.hasFocus, isTrue);
160 161 162 163 164
      expect(find.text('A FOCUSED'), findsOneWidget);

      expect(parentFocusScope, hasAGoodToStringDeep);
      expect(
        parentFocusScope.toStringDeep(),
165 166 167 168 169 170 171 172 173 174
        equalsIgnoringHashCodes(
          'FocusScopeNode#00000(Parent Scope Node [IN FOCUS PATH])\n'
          ' │ context: FocusScope\n'
          ' │ IN FOCUS PATH\n'
          ' │ focusedChildren: FocusNode#00000(Child [PRIMARY FOCUS])\n'
          ' │\n'
          ' └─Child 1: FocusNode#00000(Child [PRIMARY FOCUS])\n'
          '     context: Focus\n'
          '     PRIMARY FOCUS\n',
        ),
175 176
      );

177
      expect(FocusManager.instance.rootScope, hasAGoodToStringDeep);
178
      expect(
179
        FocusManager.instance.rootScope.toStringDeep(minLevel: DiagnosticLevel.info),
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
        equalsIgnoringHashCodes(
          'FocusScopeNode#00000(Root Focus Scope [IN FOCUS PATH])\n'
          ' │ IN FOCUS PATH\n'
          ' │ focusedChildren: FocusScopeNode#00000(Parent Scope Node [IN FOCUS\n'
          ' │   PATH])\n'
          ' │\n'
          ' └─Child 1: FocusScopeNode#00000(Parent Scope Node [IN FOCUS PATH])\n'
          '   │ context: FocusScope\n'
          '   │ IN FOCUS PATH\n'
          '   │ focusedChildren: FocusNode#00000(Child [PRIMARY FOCUS])\n'
          '   │\n'
          '   └─Child 1: FocusNode#00000(Child [PRIMARY FOCUS])\n'
          '       context: Focus\n'
          '       PRIMARY FOCUS\n',
        ),
195 196 197
      );

      // Add the child focus scope to the focus tree.
198
      final FocusAttachment childAttachment = childFocusScope.attach(key.currentContext);
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
      parentFocusScope.setFirstFocus(childFocusScope);
      await tester.pumpAndSettle();
      expect(childFocusScope.isFirstFocus, isTrue);

      // Now add the child focus scope with no child focusable in it to the tree.
      await tester.pumpWidget(
        FocusScope(
          debugLabel: 'Parent Scope',
          node: parentFocusScope,
          child: Column(
            children: <Widget>[
              TestFocus(
                key: key,
                debugLabel: 'Child',
              ),
              FocusScope(
                debugLabel: 'Child Scope',
                node: childFocusScope,
                child: Container(),
              ),
            ],
          ),
        ),
      );

224
      expect(key.currentState!.focusNode.hasFocus, isFalse);
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
      expect(find.text('a'), findsOneWidget);

      // Now move the existing focus node into the child focus scope.
      await tester.pumpWidget(
        FocusScope(
          debugLabel: 'Parent Scope',
          node: parentFocusScope,
          child: Column(
            children: <Widget>[
              FocusScope(
                debugLabel: 'Child Scope',
                node: childFocusScope,
                child: TestFocus(
                  key: key,
                  debugLabel: 'Child',
                ),
              ),
            ],
          ),
        ),
      );

      await tester.pumpAndSettle();

249
      expect(key.currentState!.focusNode.hasFocus, isFalse);
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
      expect(find.text('a'), findsOneWidget);

      // Now remove the child focus scope.
      await tester.pumpWidget(
        FocusScope(
          debugLabel: 'Parent Scope',
          node: parentFocusScope,
          child: Column(
            children: <Widget>[
              TestFocus(
                key: key,
                debugLabel: 'Child',
              ),
            ],
          ),
        ),
      );
267

268
      await tester.pumpAndSettle();
269
      expect(key.currentState!.focusNode.hasFocus, isFalse);
270
      expect(find.text('a'), findsOneWidget);
271

272 273 274 275 276
      // Must detach the child because we had to attach it in order to call
      // setFirstFocus before adding to the widget.
      childAttachment.detach();
    });

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
    testWidgets('Setting first focus requests focus for the scope properly.', (WidgetTester tester) async {
      final FocusScopeNode parentFocusScope = FocusScopeNode(debugLabel: 'Parent Scope Node');
      final FocusScopeNode childFocusScope1 = FocusScopeNode(debugLabel: 'Child Scope Node 1');
      final FocusScopeNode childFocusScope2 = FocusScopeNode(debugLabel: 'Child Scope Node 2');
      final GlobalKey<TestFocusState> keyA = GlobalKey(debugLabel: 'Key A');
      final GlobalKey<TestFocusState> keyB = GlobalKey(debugLabel: 'Key B');
      final GlobalKey<TestFocusState> keyC = GlobalKey(debugLabel: 'Key C');

      await tester.pumpWidget(
        FocusScope(
          debugLabel: 'Parent Scope',
          node: parentFocusScope,
          child: Column(
            children: <Widget>[
              FocusScope(
                debugLabel: 'Child Scope 1',
                node: childFocusScope1,
                child: Column(
                  children: <Widget>[
                    TestFocus(
                      key: keyA,
                      autofocus: true,
                      debugLabel: 'Child A',
                    ),
                    TestFocus(
                      key: keyB,
                      name: 'b',
                      debugLabel: 'Child B',
                    ),
                  ],
                ),
              ),
              FocusScope(
                debugLabel: 'Child Scope 2',
                node: childFocusScope2,
                child: TestFocus(
                  key: keyC,
                  name: 'c',
                  debugLabel: 'Child C',
                ),
              ),
            ],
          ),
        ),
      );

      await tester.pumpAndSettle();

325
      expect(keyA.currentState!.focusNode.hasFocus, isTrue);
326 327 328 329 330
      expect(find.text('A FOCUSED'), findsOneWidget);

      parentFocusScope.setFirstFocus(childFocusScope2);
      await tester.pumpAndSettle();

331
      expect(keyA.currentState!.focusNode.hasFocus, isFalse);
332 333 334 335 336
      expect(find.text('a'), findsOneWidget);

      parentFocusScope.setFirstFocus(childFocusScope1);
      await tester.pumpAndSettle();

337
      expect(keyA.currentState!.focusNode.hasFocus, isTrue);
338 339
      expect(find.text('A FOCUSED'), findsOneWidget);

340
      keyB.currentState!.focusNode.requestFocus();
341 342
      await tester.pumpAndSettle();

343
      expect(keyB.currentState!.focusNode.hasFocus, isTrue);
344 345 346 347 348 349 350
      expect(find.text('B FOCUSED'), findsOneWidget);
      expect(parentFocusScope.isFirstFocus, isTrue);
      expect(childFocusScope1.isFirstFocus, isTrue);

      parentFocusScope.setFirstFocus(childFocusScope2);
      await tester.pumpAndSettle();

351
      expect(keyB.currentState!.focusNode.hasFocus, isFalse);
352 353 354 355 356
      expect(find.text('b'), findsOneWidget);
      expect(parentFocusScope.isFirstFocus, isTrue);
      expect(childFocusScope1.isFirstFocus, isFalse);
      expect(childFocusScope2.isFirstFocus, isTrue);

357
      keyC.currentState!.focusNode.requestFocus();
358 359
      await tester.pumpAndSettle();

360
      expect(keyB.currentState!.focusNode.hasFocus, isFalse);
361
      expect(find.text('b'), findsOneWidget);
362
      expect(keyC.currentState!.focusNode.hasFocus, isTrue);
363 364 365 366 367 368 369
      expect(find.text('C FOCUSED'), findsOneWidget);
      expect(parentFocusScope.isFirstFocus, isTrue);
      expect(childFocusScope1.isFirstFocus, isFalse);
      expect(childFocusScope2.isFirstFocus, isTrue);

      childFocusScope1.requestFocus();
      await tester.pumpAndSettle();
370
      expect(keyB.currentState!.focusNode.hasFocus, isTrue);
371
      expect(find.text('B FOCUSED'), findsOneWidget);
372
      expect(keyC.currentState!.focusNode.hasFocus, isFalse);
373 374 375 376 377 378 379
      expect(find.text('c'), findsOneWidget);
      expect(parentFocusScope.isFirstFocus, isTrue);
      expect(childFocusScope1.isFirstFocus, isTrue);
      expect(childFocusScope2.isFirstFocus, isFalse);
    });

    testWidgets('Removing focused widget moves focus to next widget', (WidgetTester tester) async {
380 381 382 383 384
      final GlobalKey<TestFocusState> keyA = GlobalKey();
      final GlobalKey<TestFocusState> keyB = GlobalKey();

      await tester.pumpWidget(
        Column(
385
          children: <Widget>[
386 387 388 389 390 391
            TestFocus(
              key: keyA,
            ),
            TestFocus(
              key: keyB,
              name: 'b',
392 393 394
            ),
          ],
        ),
395
      );
396

397
      FocusScope.of(keyA.currentContext!).requestFocus(keyA.currentState!.focusNode);
398

399
      await tester.pumpAndSettle();
400

401
      expect(keyA.currentState!.focusNode.hasFocus, isTrue);
402
      expect(find.text('A FOCUSED'), findsOneWidget);
403
      expect(keyB.currentState!.focusNode.hasFocus, isFalse);
404 405 406 407
      expect(find.text('b'), findsOneWidget);

      await tester.pumpWidget(
        Column(
408
          children: <Widget>[
409 410 411 412
            TestFocus(
              key: keyB,
              name: 'b',
            ),
413 414
          ],
        ),
415
      );
416

417
      await tester.pump();
418

419
      expect(keyB.currentState!.focusNode.hasFocus, isFalse);
420 421
      expect(find.text('b'), findsOneWidget);
    });
422

423
    testWidgets('Adding a new FocusScope attaches the child to its parent.', (WidgetTester tester) async {
424 425 426
      final GlobalKey<TestFocusState> keyA = GlobalKey();
      final FocusScopeNode parentFocusScope = FocusScopeNode(debugLabel: 'Parent Scope Node');
      final FocusScopeNode childFocusScope = FocusScopeNode(debugLabel: 'Child Scope Node');
427

428 429 430 431 432
      await tester.pumpWidget(
        FocusScope(
          node: childFocusScope,
          child: TestFocus(
            debugLabel: 'Child',
433
            key: keyA,
434
          ),
435 436
        ),
      );
437

438 439 440 441
      FocusScope.of(keyA.currentContext!).requestFocus(keyA.currentState!.focusNode);
      expect(FocusScope.of(keyA.currentContext!), equals(childFocusScope));
      expect(Focus.of(keyA.currentContext!, scopeOk: true), equals(childFocusScope));
      FocusManager.instance.rootScope.setFirstFocus(FocusScope.of(keyA.currentContext!));
442

443
      await tester.pumpAndSettle();
444

445
      expect(keyA.currentState!.focusNode.hasFocus, isTrue);
446 447
      expect(find.text('A FOCUSED'), findsOneWidget);
      expect(childFocusScope.isFirstFocus, isTrue);
448

449 450 451 452 453 454 455 456 457
      await tester.pumpWidget(
        FocusScope(
          node: parentFocusScope,
          child: FocusScope(
            node: childFocusScope,
            child: TestFocus(
              debugLabel: 'Child',
              key: keyA,
            ),
458
          ),
459 460 461 462 463 464
        ),
      );

      await tester.pump();
      expect(childFocusScope.isFirstFocus, isTrue);
      // Node keeps it's focus when moved to the new scope.
465
      expect(keyA.currentState!.focusNode.hasFocus, isTrue);
466 467 468
      expect(find.text('A FOCUSED'), findsOneWidget);
    });

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
    testWidgets('Setting parentNode determines focus tree hierarchy.', (WidgetTester tester) async {
      final FocusNode topNode = FocusNode(debugLabel: 'Top');
      final FocusNode parentNode = FocusNode(debugLabel: 'Parent');
      final FocusNode childNode = FocusNode(debugLabel: 'Child');
      final FocusNode insertedNode = FocusNode(debugLabel: 'Inserted');

      await tester.pumpWidget(
        FocusScope(
          child: Focus.withExternalFocusNode(
            focusNode: topNode,
            child: Column(
              children: <Widget>[
                Focus.withExternalFocusNode(
                  focusNode: parentNode,
                  child: const SizedBox(),
                ),
                Focus.withExternalFocusNode(
                  focusNode: childNode,
                  parentNode: parentNode,
                  autofocus: true,
                  child: const SizedBox(),
                )
              ],
            ),
          ),
        ),
      );
      await tester.pump();

      expect(childNode.hasPrimaryFocus, isTrue);
      expect(parentNode.hasFocus, isTrue);
      expect(topNode.hasFocus, isTrue);

      // Check that inserting a Focus in between doesn't reparent the child.
      await tester.pumpWidget(
        FocusScope(
          child: Focus.withExternalFocusNode(
            focusNode: topNode,
            child: Column(
              children: <Widget>[
                Focus.withExternalFocusNode(
                  focusNode: parentNode,
                  child: const SizedBox(),
                ),
                Focus.withExternalFocusNode(
                  focusNode: insertedNode,
                  child: Focus.withExternalFocusNode(
                    focusNode: childNode,
                    parentNode: parentNode,
                    autofocus: true,
                    child: const SizedBox(),
                  ),
                )
              ],
            ),
          ),
        ),
      );
      await tester.pump();

      expect(childNode.hasPrimaryFocus, isTrue);
      expect(parentNode.hasFocus, isTrue);
      expect(topNode.hasFocus, isTrue);
      expect(insertedNode.hasFocus, isFalse);
    });

535 536 537 538 539 540 541 542
    testWidgets('Setting parentNode determines focus scope tree hierarchy.', (WidgetTester tester) async {
      final FocusScopeNode topNode = FocusScopeNode(debugLabel: 'Top');
      final FocusScopeNode parentNode = FocusScopeNode(debugLabel: 'Parent');
      final FocusScopeNode childNode = FocusScopeNode(debugLabel: 'Child');
      final FocusScopeNode insertedNode = FocusScopeNode(debugLabel: 'Inserted');

      await tester.pumpWidget(
        FocusScope.withExternalFocusNode(
543 544 545 546 547 548 549 550 551 552 553 554 555
          focusScopeNode: topNode,
          child: Column(
            children: <Widget>[
              FocusScope.withExternalFocusNode(
                focusScopeNode: parentNode,
                child: const SizedBox(),
              ),
              FocusScope.withExternalFocusNode(
                focusScopeNode: childNode,
                parentNode: parentNode,
                child: const Focus(
                  autofocus: true,
                  child: SizedBox(),
556
                ),
557 558
              )
            ],
559
          ),
560
        ),
561 562 563 564 565 566 567 568 569 570
      );
      await tester.pump();

      expect(childNode.hasFocus, isTrue);
      expect(parentNode.hasFocus, isTrue);
      expect(topNode.hasFocus, isTrue);

      // Check that inserting a Focus in between doesn't reparent the child.
      await tester.pumpWidget(
        FocusScope.withExternalFocusNode(
571 572 573 574 575 576 577 578 579 580 581 582 583
          focusScopeNode: topNode,
          child: Column(
            children: <Widget>[
              FocusScope.withExternalFocusNode(
                focusScopeNode: parentNode,
                child: const SizedBox(),
              ),
              FocusScope.withExternalFocusNode(
                focusScopeNode: insertedNode,
                child: FocusScope.withExternalFocusNode(
                  focusScopeNode: childNode,
                  parentNode: parentNode,
                  child: const Focus(
584 585 586
                    autofocus: true,
                    child: SizedBox(),
                  ),
587 588 589
                ),
              )
            ],
590
          ),
591
        ),
592 593 594 595 596 597 598 599 600
      );
      await tester.pump();

      expect(childNode.hasFocus, isTrue);
      expect(parentNode.hasFocus, isTrue);
      expect(topNode.hasFocus, isTrue);
      expect(insertedNode.hasFocus, isFalse);
    });

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
    // Arguably, this isn't correct behavior, but it is what happens now.
    testWidgets("Removing focused widget doesn't move focus to next widget within FocusScope", (WidgetTester tester) async {
      final GlobalKey<TestFocusState> keyA = GlobalKey();
      final GlobalKey<TestFocusState> keyB = GlobalKey();
      final FocusScopeNode parentFocusScope = FocusScopeNode(debugLabel: 'Parent Scope');

      await tester.pumpWidget(
        FocusScope(
          debugLabel: 'Parent Scope',
          node: parentFocusScope,
          autofocus: true,
          child: Column(
            children: <Widget>[
              TestFocus(
                debugLabel: 'Widget A',
                key: keyA,
              ),
              TestFocus(
                debugLabel: 'Widget B',
                key: keyB,
                name: 'b',
              ),
            ],
          ),
        ),
      );

628 629
      FocusScope.of(keyA.currentContext!).requestFocus(keyA.currentState!.focusNode);
      final FocusScopeNode scope = FocusScope.of(keyA.currentContext!);
630
      FocusManager.instance.rootScope.setFirstFocus(scope);
631 632 633

      await tester.pumpAndSettle();

634
      expect(keyA.currentState!.focusNode.hasFocus, isTrue);
635
      expect(find.text('A FOCUSED'), findsOneWidget);
636
      expect(keyB.currentState!.focusNode.hasFocus, isFalse);
637 638 639 640 641 642 643 644 645 646 647 648 649 650 651
      expect(find.text('b'), findsOneWidget);

      await tester.pumpWidget(
        FocusScope(
          node: parentFocusScope,
          child: Column(
            children: <Widget>[
              TestFocus(
                key: keyB,
                name: 'b',
              ),
            ],
          ),
        ),
      );
652

653
      await tester.pump();
654

655
      expect(keyB.currentState!.focusNode.hasFocus, isFalse);
656 657
      expect(find.text('b'), findsOneWidget);
    });
658

659 660 661 662 663 664
    testWidgets('Removing a FocusScope removes its node from the tree', (WidgetTester tester) async {
      final GlobalKey<TestFocusState> keyA = GlobalKey();
      final GlobalKey<TestFocusState> keyB = GlobalKey();
      final GlobalKey<TestFocusState> scopeKeyA = GlobalKey();
      final GlobalKey<TestFocusState> scopeKeyB = GlobalKey();
      final FocusScopeNode parentFocusScope = FocusScopeNode(debugLabel: 'Parent Scope');
665

666 667 668
      // This checks both FocusScopes that have their own nodes, as well as those
      // that use external nodes.
      await tester.pumpWidget(
669
        FocusTraversalGroup(
670 671 672 673 674 675 676 677 678 679 680 681 682
          child: Column(
            children: <Widget>[
              FocusScope(
                key: scopeKeyA,
                node: parentFocusScope,
                child: Column(
                  children: <Widget>[
                    TestFocus(
                      debugLabel: 'Child A',
                      key: keyA,
                    ),
                  ],
                ),
683
              ),
684 685 686 687 688 689 690 691 692 693 694
              FocusScope(
                key: scopeKeyB,
                child: Column(
                  children: <Widget>[
                    TestFocus(
                      debugLabel: 'Child B',
                      key: keyB,
                      name: 'b',
                    ),
                  ],
                ),
695
              ),
696 697
            ],
          ),
698
        ),
699
      );
700

701 702 703 704
      FocusScope.of(keyB.currentContext!).requestFocus(keyB.currentState!.focusNode);
      FocusScope.of(keyA.currentContext!).requestFocus(keyA.currentState!.focusNode);
      final FocusScopeNode aScope = FocusScope.of(keyA.currentContext!);
      final FocusScopeNode bScope = FocusScope.of(keyB.currentContext!);
705 706
      FocusManager.instance.rootScope.setFirstFocus(bScope);
      FocusManager.instance.rootScope.setFirstFocus(aScope);
707

708
      await tester.pumpAndSettle();
709

710 711
      expect(FocusScope.of(keyA.currentContext!).isFirstFocus, isTrue);
      expect(keyA.currentState!.focusNode.hasFocus, isTrue);
712
      expect(find.text('A FOCUSED'), findsOneWidget);
713
      expect(keyB.currentState!.focusNode.hasFocus, isFalse);
714
      expect(find.text('b'), findsOneWidget);
715

716
      await tester.pumpWidget(Container());
717

718
      expect(FocusManager.instance.rootScope.children, isEmpty);
719
    });
720

721 722 723 724 725 726 727 728 729 730
    // By "pinned", it means kept in the tree by a GlobalKey.
    testWidgets("Removing pinned focused scope doesn't move focus to focused widget within next FocusScope", (WidgetTester tester) async {
      final GlobalKey<TestFocusState> keyA = GlobalKey();
      final GlobalKey<TestFocusState> keyB = GlobalKey();
      final GlobalKey<TestFocusState> scopeKeyA = GlobalKey();
      final GlobalKey<TestFocusState> scopeKeyB = GlobalKey();
      final FocusScopeNode parentFocusScope1 = FocusScopeNode(debugLabel: 'Parent Scope 1');
      final FocusScopeNode parentFocusScope2 = FocusScopeNode(debugLabel: 'Parent Scope 2');

      await tester.pumpWidget(
731
        FocusTraversalGroup(
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
          child: Column(
            children: <Widget>[
              FocusScope(
                key: scopeKeyA,
                node: parentFocusScope1,
                child: Column(
                  children: <Widget>[
                    TestFocus(
                      debugLabel: 'Child A',
                      key: keyA,
                    ),
                  ],
                ),
              ),
              FocusScope(
                key: scopeKeyB,
                node: parentFocusScope2,
                child: Column(
                  children: <Widget>[
                    TestFocus(
                      debugLabel: 'Child B',
                      key: keyB,
                      name: 'b',
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      );

764 765 766 767
      FocusScope.of(keyB.currentContext!).requestFocus(keyB.currentState!.focusNode);
      FocusScope.of(keyA.currentContext!).requestFocus(keyA.currentState!.focusNode);
      final FocusScopeNode bScope = FocusScope.of(keyB.currentContext!);
      final FocusScopeNode aScope = FocusScope.of(keyA.currentContext!);
768 769
      FocusManager.instance.rootScope.setFirstFocus(bScope);
      FocusManager.instance.rootScope.setFirstFocus(aScope);
770 771 772

      await tester.pumpAndSettle();

773 774
      expect(FocusScope.of(keyA.currentContext!).isFirstFocus, isTrue);
      expect(keyA.currentState!.focusNode.hasFocus, isTrue);
775
      expect(find.text('A FOCUSED'), findsOneWidget);
776
      expect(keyB.currentState!.focusNode.hasFocus, isFalse);
777 778 779
      expect(find.text('b'), findsOneWidget);

      await tester.pumpWidget(
780
        FocusTraversalGroup(
781 782 783 784 785 786 787 788
          child: Column(
            children: <Widget>[
              FocusScope(
                key: scopeKeyB,
                node: parentFocusScope2,
                child: Column(
                  children: <Widget>[
                    TestFocus(
789
                      debugLabel: 'Child B',
790 791 792 793 794 795 796 797 798 799 800 801 802 803
                      key: keyB,
                      name: 'b',
                      autofocus: true,
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      );

      await tester.pump();

804
      expect(keyB.currentState!.focusNode.hasFocus, isTrue);
805
      expect(find.text('B FOCUSED'), findsOneWidget);
806 807
    });

808 809 810 811 812
    testWidgets("Removing unpinned focused scope doesn't move focus to focused widget within next FocusScope", (WidgetTester tester) async {
      final GlobalKey<TestFocusState> keyA = GlobalKey();
      final GlobalKey<TestFocusState> keyB = GlobalKey();
      final FocusScopeNode parentFocusScope1 = FocusScopeNode(debugLabel: 'Parent Scope 1');
      final FocusScopeNode parentFocusScope2 = FocusScopeNode(debugLabel: 'Parent Scope 2');
813

814
      await tester.pumpWidget(
815
        FocusTraversalGroup(
816 817 818 819 820 821 822 823 824 825 826 827
          child: Column(
            children: <Widget>[
              FocusScope(
                node: parentFocusScope1,
                child: Column(
                  children: <Widget>[
                    TestFocus(
                      debugLabel: 'Child A',
                      key: keyA,
                    ),
                  ],
                ),
828
              ),
829 830 831 832 833 834 835 836 837 838 839
              FocusScope(
                node: parentFocusScope2,
                child: Column(
                  children: <Widget>[
                    TestFocus(
                      debugLabel: 'Child B',
                      key: keyB,
                      name: 'b',
                    ),
                  ],
                ),
840
              ),
841 842
            ],
          ),
843
        ),
844 845
      );

846 847 848 849
      FocusScope.of(keyB.currentContext!).requestFocus(keyB.currentState!.focusNode);
      FocusScope.of(keyA.currentContext!).requestFocus(keyA.currentState!.focusNode);
      final FocusScopeNode bScope = FocusScope.of(keyB.currentContext!);
      final FocusScopeNode aScope = FocusScope.of(keyA.currentContext!);
850 851
      FocusManager.instance.rootScope.setFirstFocus(bScope);
      FocusManager.instance.rootScope.setFirstFocus(aScope);
852 853 854

      await tester.pumpAndSettle();

855 856
      expect(FocusScope.of(keyA.currentContext!).isFirstFocus, isTrue);
      expect(keyA.currentState!.focusNode.hasFocus, isTrue);
857
      expect(find.text('A FOCUSED'), findsOneWidget);
858
      expect(keyB.currentState!.focusNode.hasFocus, isFalse);
859 860 861
      expect(find.text('b'), findsOneWidget);

      await tester.pumpWidget(
862
        FocusTraversalGroup(
863 864 865 866 867 868 869
          child: Column(
            children: <Widget>[
              FocusScope(
                node: parentFocusScope2,
                child: Column(
                  children: <Widget>[
                    TestFocus(
870
                      debugLabel: 'Child B',
871 872 873 874 875 876
                      key: keyB,
                      name: 'b',
                      autofocus: true,
                    ),
                  ],
                ),
877
              ),
878 879
            ],
          ),
880
        ),
881 882
      );
      await tester.pump();
883

884
      expect(keyB.currentState!.focusNode.hasFocus, isTrue);
885
      expect(find.text('B FOCUSED'), findsOneWidget);
886
    });
887

888 889 890 891 892
    testWidgets('Moving widget from one scope to another retains focus', (WidgetTester tester) async {
      final FocusScopeNode parentFocusScope1 = FocusScopeNode();
      final FocusScopeNode parentFocusScope2 = FocusScopeNode();
      final GlobalKey<TestFocusState> keyA = GlobalKey();
      final GlobalKey<TestFocusState> keyB = GlobalKey();
893

894 895 896 897 898 899 900 901 902 903 904 905
      await tester.pumpWidget(
        Column(
          children: <Widget>[
            FocusScope(
              node: parentFocusScope1,
              child: Column(
                children: <Widget>[
                  TestFocus(
                    key: keyA,
                  ),
                ],
              ),
906
            ),
907 908 909 910 911 912 913 914 915 916
            FocusScope(
              node: parentFocusScope2,
              child: Column(
                children: <Widget>[
                  TestFocus(
                    key: keyB,
                    name: 'b',
                  ),
                ],
              ),
917
            ),
918 919 920
          ],
        ),
      );
921

922 923
      FocusScope.of(keyA.currentContext!).requestFocus(keyA.currentState!.focusNode);
      final FocusScopeNode aScope = FocusScope.of(keyA.currentContext!);
924
      FocusManager.instance.rootScope.setFirstFocus(aScope);
925

926
      await tester.pumpAndSettle();
927

928
      expect(keyA.currentState!.focusNode.hasFocus, isTrue);
929
      expect(find.text('A FOCUSED'), findsOneWidget);
930
      expect(keyB.currentState!.focusNode.hasFocus, isFalse);
931
      expect(find.text('b'), findsOneWidget);
932

933 934 935 936 937 938 939 940 941 942 943 944 945
      await tester.pumpWidget(
        Column(
          children: <Widget>[
            FocusScope(
              node: parentFocusScope1,
              child: Column(
                children: <Widget>[
                  TestFocus(
                    key: keyB,
                    name: 'b',
                  ),
                ],
              ),
946
            ),
947 948 949 950 951 952 953 954 955 956 957 958 959
            FocusScope(
              node: parentFocusScope2,
              child: Column(
                children: <Widget>[
                  TestFocus(
                    key: keyA,
                  ),
                ],
              ),
            ),
          ],
        ),
      );
960

961
      await tester.pump();
962

963
      expect(keyA.currentState!.focusNode.hasFocus, isTrue);
964
      expect(find.text('A FOCUSED'), findsOneWidget);
965
      expect(keyB.currentState!.focusNode.hasFocus, isFalse);
966 967
      expect(find.text('b'), findsOneWidget);
    });
968

969 970 971 972 973
    testWidgets('Moving FocusScopeNodes retains focus', (WidgetTester tester) async {
      final FocusScopeNode parentFocusScope1 = FocusScopeNode(debugLabel: 'Scope 1');
      final FocusScopeNode parentFocusScope2 = FocusScopeNode(debugLabel: 'Scope 2');
      final GlobalKey<TestFocusState> keyA = GlobalKey();
      final GlobalKey<TestFocusState> keyB = GlobalKey();
974

975 976 977 978 979 980 981 982 983 984 985 986 987
      await tester.pumpWidget(
        Column(
          children: <Widget>[
            FocusScope(
              node: parentFocusScope1,
              child: Column(
                children: <Widget>[
                  TestFocus(
                    debugLabel: 'Child A',
                    key: keyA,
                  ),
                ],
              ),
988
            ),
989 990 991 992 993 994 995 996 997 998 999
            FocusScope(
              node: parentFocusScope2,
              child: Column(
                children: <Widget>[
                  TestFocus(
                    debugLabel: 'Child B',
                    key: keyB,
                    name: 'b',
                  ),
                ],
              ),
1000
            ),
1001 1002 1003
          ],
        ),
      );
1004

1005 1006
      FocusScope.of(keyA.currentContext!).requestFocus(keyA.currentState!.focusNode);
      final FocusScopeNode aScope = FocusScope.of(keyA.currentContext!);
1007
      FocusManager.instance.rootScope.setFirstFocus(aScope);
1008

1009
      await tester.pumpAndSettle();
1010

1011
      expect(keyA.currentState!.focusNode.hasFocus, isTrue);
1012
      expect(find.text('A FOCUSED'), findsOneWidget);
1013
      expect(keyB.currentState!.focusNode.hasFocus, isFalse);
1014
      expect(find.text('b'), findsOneWidget);
1015

1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029
      // This just swaps the FocusScopeNodes that the FocusScopes have in them.
      await tester.pumpWidget(
        Column(
          children: <Widget>[
            FocusScope(
              node: parentFocusScope2,
              child: Column(
                children: <Widget>[
                  TestFocus(
                    debugLabel: 'Child A',
                    key: keyA,
                  ),
                ],
              ),
1030
            ),
1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045
            FocusScope(
              node: parentFocusScope1,
              child: Column(
                children: <Widget>[
                  TestFocus(
                    debugLabel: 'Child B',
                    key: keyB,
                    name: 'b',
                  ),
                ],
              ),
            ),
          ],
        ),
      );
1046

1047
      await tester.pump();
1048

1049
      expect(keyA.currentState!.focusNode.hasFocus, isTrue);
1050
      expect(find.text('A FOCUSED'), findsOneWidget);
1051
      expect(keyB.currentState!.focusNode.hasFocus, isFalse);
1052 1053
      expect(find.text('b'), findsOneWidget);
    });
1054

1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070
    testWidgets('Can focus root node.', (WidgetTester tester) async {
      final GlobalKey key1 = GlobalKey(debugLabel: '1');
      await tester.pumpWidget(
        Focus(
          key: key1,
          child: Container(),
        ),
      );

      final Element firstElement = tester.element(find.byKey(key1));
      final FocusScopeNode rootNode = FocusScope.of(firstElement);
      rootNode.requestFocus();

      await tester.pump();

      expect(rootNode.hasFocus, isTrue);
1071
      expect(rootNode, equals(firstElement.owner!.focusManager.rootScope));
1072
    });
1073

1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096
    testWidgets('Can autofocus a node.', (WidgetTester tester) async {
      final FocusNode focusNode = FocusNode(debugLabel: 'Test Node');
      await tester.pumpWidget(
        Focus(
          focusNode: focusNode,
          child: Container(),
        ),
      );

      await tester.pump();
      expect(focusNode.hasPrimaryFocus, isFalse);

      await tester.pumpWidget(
        Focus(
          autofocus: true,
          focusNode: focusNode,
          child: Container(),
        ),
      );

      await tester.pump();
      expect(focusNode.hasPrimaryFocus, isTrue);
    });
1097

1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135
    testWidgets("Won't autofocus a node if one is already focused.", (WidgetTester tester) async {
      final FocusNode focusNodeA = FocusNode(debugLabel: 'Test Node A');
      final FocusNode focusNodeB = FocusNode(debugLabel: 'Test Node B');
      await tester.pumpWidget(
        Column(
          children: <Widget>[
            Focus(
              focusNode: focusNodeA,
              autofocus: true,
              child: Container(),
            ),
          ],
        ),
      );

      await tester.pump();
      expect(focusNodeA.hasPrimaryFocus, isTrue);

      await tester.pumpWidget(
        Column(
          children: <Widget>[
            Focus(
              focusNode: focusNodeA,
              child: Container(),
            ),
            Focus(
              focusNode: focusNodeB,
              autofocus: true,
              child: Container(),
            ),
          ],
        ),
      );

      await tester.pump();
      expect(focusNodeB.hasPrimaryFocus, isFalse);
      expect(focusNodeA.hasPrimaryFocus, isTrue);
    });
1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153

    testWidgets("FocusScope doesn't update the focusNode attributes when the widget updates if withExternalFocusNode is used", (WidgetTester tester) async {
      final GlobalKey key1 = GlobalKey(debugLabel: '1');
      final FocusScopeNode focusScopeNode = FocusScopeNode();
      bool? keyEventHandled;
      KeyEventResult handleCallback(FocusNode node, RawKeyEvent event) {
        keyEventHandled = true;
        return KeyEventResult.handled;
      }
      KeyEventResult handleEventCallback(FocusNode node, KeyEvent event) {
        keyEventHandled = true;
        return KeyEventResult.handled;
      }
      KeyEventResult ignoreCallback(FocusNode node, RawKeyEvent event) => KeyEventResult.ignored;
      KeyEventResult ignoreEventCallback(FocusNode node, KeyEvent event) => KeyEventResult.ignored;
      focusScopeNode.onKey = ignoreCallback;
      focusScopeNode.onKeyEvent = ignoreEventCallback;
      focusScopeNode.descendantsAreFocusable = false;
1154
      focusScopeNode.descendantsAreTraversable = false;
1155 1156 1157 1158 1159 1160 1161 1162 1163 1164
      focusScopeNode.skipTraversal = false;
      focusScopeNode.canRequestFocus = true;
      FocusScope focusScopeWidget = FocusScope.withExternalFocusNode(
        focusScopeNode: focusScopeNode,
        child: Container(key: key1),
      );
      await tester.pumpWidget(focusScopeWidget);
      expect(focusScopeNode.onKey, equals(ignoreCallback));
      expect(focusScopeNode.onKeyEvent, equals(ignoreEventCallback));
      expect(focusScopeNode.descendantsAreFocusable, isFalse);
1165
      expect(focusScopeNode.descendantsAreTraversable, isFalse);
1166 1167 1168 1169 1170
      expect(focusScopeNode.skipTraversal, isFalse);
      expect(focusScopeNode.canRequestFocus, isTrue);
      expect(focusScopeWidget.onKey, equals(focusScopeNode.onKey));
      expect(focusScopeWidget.onKeyEvent, equals(focusScopeNode.onKeyEvent));
      expect(focusScopeWidget.descendantsAreFocusable, equals(focusScopeNode.descendantsAreFocusable));
1171
      expect(focusScopeWidget.descendantsAreTraversable, equals(focusScopeNode.descendantsAreTraversable));
1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182
      expect(focusScopeWidget.skipTraversal, equals(focusScopeNode.skipTraversal));
      expect(focusScopeWidget.canRequestFocus, equals(focusScopeNode.canRequestFocus));

      FocusScope.of(key1.currentContext!).requestFocus();
      await tester.pump();
      await tester.sendKeyEvent(LogicalKeyboardKey.enter);
      expect(keyEventHandled, isNull);

      focusScopeNode.onKey = handleCallback;
      focusScopeNode.onKeyEvent = handleEventCallback;
      focusScopeNode.descendantsAreFocusable = true;
1183
      focusScopeNode.descendantsAreTraversable = true;
1184 1185 1186 1187 1188 1189 1190 1191
      focusScopeWidget = FocusScope.withExternalFocusNode(
        focusScopeNode: focusScopeNode,
        child: Container(key: key1),
      );
      await tester.pumpWidget(focusScopeWidget);
      expect(focusScopeNode.onKey, equals(handleCallback));
      expect(focusScopeNode.onKeyEvent, equals(handleEventCallback));
      expect(focusScopeNode.descendantsAreFocusable, isTrue);
1192
      expect(focusScopeNode.descendantsAreTraversable, isTrue);
1193 1194 1195 1196 1197
      expect(focusScopeNode.skipTraversal, isFalse);
      expect(focusScopeNode.canRequestFocus, isTrue);
      expect(focusScopeWidget.onKey, equals(focusScopeNode.onKey));
      expect(focusScopeWidget.onKeyEvent, equals(focusScopeNode.onKeyEvent));
      expect(focusScopeWidget.descendantsAreFocusable, equals(focusScopeNode.descendantsAreFocusable));
1198
      expect(focusScopeWidget.descendantsAreTraversable, equals(focusScopeNode.descendantsAreTraversable));
1199 1200 1201 1202 1203 1204
      expect(focusScopeWidget.skipTraversal, equals(focusScopeNode.skipTraversal));
      expect(focusScopeWidget.canRequestFocus, equals(focusScopeNode.canRequestFocus));

      await tester.sendKeyEvent(LogicalKeyboardKey.enter);
      expect(keyEventHandled, isTrue);
    });
1205
  });
1206

1207
  group('Focus', () {
1208
    testWidgets('Focus.of stops at the nearest Focus widget.', (WidgetTester tester) async {
1209 1210 1211 1212 1213 1214
      final GlobalKey key1 = GlobalKey(debugLabel: '1');
      final GlobalKey key2 = GlobalKey(debugLabel: '2');
      final GlobalKey key3 = GlobalKey(debugLabel: '3');
      final GlobalKey key4 = GlobalKey(debugLabel: '4');
      final GlobalKey key5 = GlobalKey(debugLabel: '5');
      final GlobalKey key6 = GlobalKey(debugLabel: '6');
1215
      final FocusScopeNode scopeNode = FocusScopeNode();
1216
      await tester.pumpWidget(
1217
        FocusScope(
1218
          key: key1,
1219
          node: scopeNode,
1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233
          debugLabel: 'Key 1',
          child: Container(
            key: key2,
            child: Focus(
              debugLabel: 'Key 3',
              key: key3,
              child: Container(
                key: key4,
                child: Focus(
                  debugLabel: 'Key 5',
                  key: key5,
                  child: Container(
                    key: key6,
                  ),
1234
                ),
1235
              ),
1236 1237
            ),
          ),
1238 1239 1240 1241 1242 1243 1244 1245
        ),
      );
      final Element element1 = tester.element(find.byKey(key1));
      final Element element2 = tester.element(find.byKey(key2));
      final Element element3 = tester.element(find.byKey(key3));
      final Element element4 = tester.element(find.byKey(key4));
      final Element element5 = tester.element(find.byKey(key5));
      final Element element6 = tester.element(find.byKey(key6));
1246
      final FocusNode root = element1.owner!.focusManager.rootScope;
1247

1248 1249 1250 1251 1252 1253
      expect(Focus.maybeOf(element1), isNull);
      expect(Focus.maybeOf(element2), isNull);
      expect(Focus.maybeOf(element3), isNull);
      expect(Focus.of(element4).parent!.parent, equals(root));
      expect(Focus.of(element5).parent!.parent, equals(root));
      expect(Focus.of(element6).parent!.parent!.parent, equals(root));
1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270
    });
    testWidgets('Can traverse Focus children.', (WidgetTester tester) async {
      final GlobalKey key1 = GlobalKey(debugLabel: '1');
      final GlobalKey key2 = GlobalKey(debugLabel: '2');
      final GlobalKey key3 = GlobalKey(debugLabel: '3');
      final GlobalKey key4 = GlobalKey(debugLabel: '4');
      final GlobalKey key5 = GlobalKey(debugLabel: '5');
      final GlobalKey key6 = GlobalKey(debugLabel: '6');
      final GlobalKey key7 = GlobalKey(debugLabel: '7');
      final GlobalKey key8 = GlobalKey(debugLabel: '8');
      await tester.pumpWidget(
        Focus(
          child: Column(
            key: key1,
            children: <Widget>[
              Focus(
                key: key2,
1271 1272 1273
                child: Focus(
                  key: key3,
                  child: Container(),
1274
                ),
1275 1276 1277
              ),
              Focus(
                key: key4,
1278 1279 1280
                child: Focus(
                  key: key5,
                  child: Container(),
1281
                ),
1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295
              ),
              Focus(
                key: key6,
                child: Column(
                  children: <Widget>[
                    Focus(
                      key: key7,
                      child: Container(),
                    ),
                    Focus(
                      key: key8,
                      child: Container(),
                    ),
                  ],
1296
                ),
1297 1298
              ),
            ],
1299
          ),
1300 1301 1302 1303 1304 1305 1306 1307
        ),
      );

      final Element firstScope = tester.element(find.byKey(key1));
      final List<FocusNode> nodes = <FocusNode>[];
      final List<Key> keys = <Key>[];
      bool visitor(FocusNode node) {
        nodes.add(node);
1308
        keys.add(node.context!.widget.key!);
1309 1310 1311 1312 1313
        return true;
      }

      await tester.pump();

1314
      Focus.of(firstScope).descendants.forEach(visitor);
1315 1316 1317 1318 1319 1320 1321 1322 1323
      expect(nodes.length, equals(7));
      expect(keys.length, equals(7));
      // Depth first.
      expect(keys, equals(<Key>[key3, key2, key5, key4, key7, key8, key6]));

      // Just traverses a sub-tree.
      final Element secondScope = tester.element(find.byKey(key7));
      nodes.clear();
      keys.clear();
1324
      Focus.of(secondScope).descendants.forEach(visitor);
1325 1326 1327
      expect(nodes.length, equals(2));
      expect(keys, equals(<Key>[key7, key8]));
    });
1328

1329 1330
    testWidgets('Can set focus.', (WidgetTester tester) async {
      final GlobalKey key1 = GlobalKey(debugLabel: '1');
1331
      late bool gotFocus;
1332 1333 1334 1335 1336 1337 1338 1339
      await tester.pumpWidget(
        Focus(
          onFocusChange: (bool focused) => gotFocus = focused,
          child: Container(key: key1),
        ),
      );

      final Element firstNode = tester.element(find.byKey(key1));
1340
      final FocusNode node = Focus.of(firstNode);
1341 1342 1343 1344 1345 1346 1347
      node.requestFocus();

      await tester.pump();

      expect(gotFocus, isTrue);
      expect(node.hasFocus, isTrue);
    });
1348

1349 1350
    testWidgets('Focus is ignored when set to not focusable.', (WidgetTester tester) async {
      final GlobalKey key1 = GlobalKey(debugLabel: '1');
1351
      bool? gotFocus;
1352 1353 1354 1355 1356 1357 1358 1359 1360
      await tester.pumpWidget(
        Focus(
          canRequestFocus: false,
          onFocusChange: (bool focused) => gotFocus = focused,
          child: Container(key: key1),
        ),
      );

      final Element firstNode = tester.element(find.byKey(key1));
1361
      final FocusNode node = Focus.of(firstNode);
1362 1363 1364 1365 1366 1367 1368
      node.requestFocus();

      await tester.pump();

      expect(gotFocus, isNull);
      expect(node.hasFocus, isFalse);
    });
1369

1370 1371
    testWidgets('Focus is lost when set to not focusable.', (WidgetTester tester) async {
      final GlobalKey key1 = GlobalKey(debugLabel: '1');
1372
      bool? gotFocus;
1373 1374 1375 1376 1377 1378 1379 1380 1381 1382
      await tester.pumpWidget(
        Focus(
          autofocus: true,
          canRequestFocus: true,
          onFocusChange: (bool focused) => gotFocus = focused,
          child: Container(key: key1),
        ),
      );

      Element firstNode = tester.element(find.byKey(key1));
1383
      FocusNode node = Focus.of(firstNode);
1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400
      node.requestFocus();

      await tester.pump();

      expect(gotFocus, isTrue);
      expect(node.hasFocus, isTrue);

      gotFocus = null;
      await tester.pumpWidget(
        Focus(
          canRequestFocus: false,
          onFocusChange: (bool focused) => gotFocus = focused,
          child: Container(key: key1),
        ),
      );

      firstNode = tester.element(find.byKey(key1));
1401
      node = Focus.of(firstNode);
1402 1403 1404 1405 1406 1407 1408
      node.requestFocus();

      await tester.pump();

      expect(gotFocus, false);
      expect(node.hasFocus, isFalse);
    });
1409

1410 1411 1412 1413
    testWidgets('Child of unfocusable Focus can get focus.', (WidgetTester tester) async {
      final GlobalKey key1 = GlobalKey(debugLabel: '1');
      final GlobalKey key2 = GlobalKey(debugLabel: '2');
      final FocusNode focusNode = FocusNode();
1414
      bool? gotFocus;
1415 1416 1417 1418 1419 1420 1421 1422 1423
      await tester.pumpWidget(
        Focus(
          canRequestFocus: false,
          onFocusChange: (bool focused) => gotFocus = focused,
          child: Focus(key: key1, focusNode: focusNode, child: Container(key: key2)),
        ),
      );

      final Element childWidget = tester.element(find.byKey(key1));
1424
      final FocusNode unfocusableNode = Focus.of(childWidget);
1425 1426 1427 1428 1429 1430 1431 1432
      unfocusableNode.requestFocus();

      await tester.pump();

      expect(gotFocus, isNull);
      expect(unfocusableNode.hasFocus, isFalse);

      final Element containerWidget = tester.element(find.byKey(key2));
1433
      final FocusNode focusableNode = Focus.of(containerWidget);
1434 1435 1436 1437 1438 1439 1440
      focusableNode.requestFocus();

      await tester.pump();

      expect(gotFocus, isTrue);
      expect(unfocusableNode.hasFocus, isTrue);
    });
1441

1442 1443
    testWidgets('Nodes are removed when all Focuses are removed.', (WidgetTester tester) async {
      final GlobalKey key1 = GlobalKey(debugLabel: '1');
1444
      late bool gotFocus;
1445 1446 1447 1448 1449 1450 1451 1452
      await tester.pumpWidget(
        FocusScope(
          child: Focus(
            onFocusChange: (bool focused) => gotFocus = focused,
            child: Container(key: key1),
          ),
        ),
      );
1453

1454
      final Element firstNode = tester.element(find.byKey(key1));
1455
      final FocusNode node = Focus.of(firstNode);
1456
      node.requestFocus();
1457

1458
      await tester.pump();
1459

1460 1461
      expect(gotFocus, isTrue);
      expect(node.hasFocus, isTrue);
1462

1463
      await tester.pumpWidget(Container());
1464

1465 1466
      expect(FocusManager.instance.rootScope.descendants, isEmpty);
    });
1467

1468 1469
    testWidgets('Focus widgets set Semantics information about focus', (WidgetTester tester) async {
      final GlobalKey<TestFocusState> key = GlobalKey();
1470

1471
      await tester.pumpWidget(
1472
        TestFocus(key: key),
1473
      );
1474

1475
      final SemanticsNode semantics = tester.getSemantics(find.byKey(key));
1476

1477
      expect(key.currentState!.focusNode.hasFocus, isFalse);
1478 1479
      expect(semantics.hasFlag(SemanticsFlag.isFocused), isFalse);
      expect(semantics.hasFlag(SemanticsFlag.isFocusable), isTrue);
1480

1481
      FocusScope.of(key.currentContext!).requestFocus(key.currentState!.focusNode);
1482
      await tester.pumpAndSettle();
1483

1484
      expect(key.currentState!.focusNode.hasFocus, isTrue);
1485 1486
      expect(semantics.hasFlag(SemanticsFlag.isFocused), isTrue);
      expect(semantics.hasFlag(SemanticsFlag.isFocusable), isTrue);
1487

1488
      key.currentState!.focusNode.canRequestFocus = false;
1489
      await tester.pumpAndSettle();
1490

1491 1492
      expect(key.currentState!.focusNode.hasFocus, isFalse);
      expect(key.currentState!.focusNode.canRequestFocus, isFalse);
1493 1494 1495
      expect(semantics.hasFlag(SemanticsFlag.isFocused), isFalse);
      expect(semantics.hasFlag(SemanticsFlag.isFocusable), isFalse);
    });
1496

1497 1498
    testWidgets('Setting canRequestFocus on focus node causes update.', (WidgetTester tester) async {
      final GlobalKey<TestFocusState> key = GlobalKey();
1499

1500
      final TestFocus testFocus = TestFocus(key: key);
1501
      await tester.pumpWidget(
1502 1503 1504 1505
        testFocus,
      );

      await tester.pumpAndSettle();
1506 1507
      key.currentState!.built = false;
      key.currentState!.focusNode.canRequestFocus = false;
1508
      await tester.pumpAndSettle();
1509
      key.currentState!.built = true;
1510

1511
      expect(key.currentState!.focusNode.canRequestFocus, isFalse);
1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532
    });

    testWidgets('canRequestFocus causes descendants of scope to be skipped.', (WidgetTester tester) async {
      final GlobalKey scope1 = GlobalKey(debugLabel: 'scope1');
      final GlobalKey scope2 = GlobalKey(debugLabel: 'scope2');
      final GlobalKey focus1 = GlobalKey(debugLabel: 'focus1');
      final GlobalKey focus2 = GlobalKey(debugLabel: 'focus2');
      final GlobalKey container1 = GlobalKey(debugLabel: 'container');
      Future<void> pumpTest({
        bool allowScope1 = true,
        bool allowScope2 = true,
        bool allowFocus1 = true,
        bool allowFocus2 = true,
      }) async {
        await tester.pumpWidget(
          FocusScope(
            key: scope1,
            canRequestFocus: allowScope1,
            child: FocusScope(
              key: scope2,
              canRequestFocus: allowScope2,
1533
              child: Focus(
1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551
                key: focus1,
                canRequestFocus: allowFocus1,
                child: Focus(
                  key: focus2,
                  canRequestFocus: allowFocus2,
                  child: Container(
                    key: container1,
                  ),
                ),
              ),
            ),
          ),
        );
        await tester.pump();
      }

      // Check childless node (focus2).
      await pumpTest();
1552
      Focus.of(container1.currentContext!).requestFocus();
1553
      await tester.pump();
1554
      expect(Focus.of(container1.currentContext!).hasFocus, isTrue);
1555
      await pumpTest(allowFocus2: false);
1556 1557
      expect(Focus.of(container1.currentContext!).hasFocus, isFalse);
      Focus.of(container1.currentContext!).requestFocus();
1558
      await tester.pump();
1559
      expect(Focus.of(container1.currentContext!).hasFocus, isFalse);
1560
      await pumpTest();
1561
      Focus.of(container1.currentContext!).requestFocus();
1562
      await tester.pump();
1563
      expect(Focus.of(container1.currentContext!).hasFocus, isTrue);
1564 1565 1566

      // Check FocusNode with child (focus1). Shouldn't affect children.
      await pumpTest(allowFocus1: false);
1567 1568
      expect(Focus.of(container1.currentContext!).hasFocus, isTrue); // focus2 has focus.
      Focus.of(focus2.currentContext!).requestFocus(); // Try to focus focus1
1569
      await tester.pump();
1570 1571
      expect(Focus.of(container1.currentContext!).hasFocus, isTrue); // focus2 still has focus.
      Focus.of(container1.currentContext!).requestFocus(); // Now try to focus focus2
1572
      await tester.pump();
1573
      expect(Focus.of(container1.currentContext!).hasFocus, isTrue);
1574 1575
      await pumpTest();
      // Try again, now that we've set focus1's canRequestFocus to true again.
1576
      Focus.of(container1.currentContext!).unfocus();
1577
      await tester.pump();
1578 1579
      expect(Focus.of(container1.currentContext!).hasFocus, isFalse);
      Focus.of(container1.currentContext!).requestFocus();
1580
      await tester.pump();
1581
      expect(Focus.of(container1.currentContext!).hasFocus, isTrue);
1582 1583 1584

      // Check FocusScopeNode with only FocusNode children (scope2). Should affect children.
      await pumpTest(allowScope2: false);
1585
      expect(Focus.of(container1.currentContext!).hasFocus, isFalse);
1586
      FocusScope.of(focus1.currentContext!).requestFocus(); // Try to focus scope2
1587
      await tester.pump();
1588 1589
      expect(Focus.of(container1.currentContext!).hasFocus, isFalse);
      Focus.of(focus2.currentContext!).requestFocus(); // Try to focus focus1
1590
      await tester.pump();
1591 1592
      expect(Focus.of(container1.currentContext!).hasFocus, isFalse);
      Focus.of(container1.currentContext!).requestFocus(); // Try to focus focus2
1593
      await tester.pump();
1594
      expect(Focus.of(container1.currentContext!).hasFocus, isFalse);
1595 1596
      await pumpTest();
      // Try again, now that we've set scope2's canRequestFocus to true again.
1597
      Focus.of(container1.currentContext!).requestFocus();
1598
      await tester.pump();
1599
      expect(Focus.of(container1.currentContext!).hasFocus, isTrue);
1600 1601 1602

      // Check FocusScopeNode with both FocusNode children and FocusScope children (scope1). Should affect children.
      await pumpTest(allowScope1: false);
1603
      expect(Focus.of(container1.currentContext!).hasFocus, isFalse);
1604
      FocusScope.of(scope2.currentContext!).requestFocus(); // Try to focus scope1
1605
      await tester.pump();
1606
      expect(Focus.of(container1.currentContext!).hasFocus, isFalse);
1607
      FocusScope.of(focus1.currentContext!).requestFocus(); // Try to focus scope2
1608
      await tester.pump();
1609 1610
      expect(Focus.of(container1.currentContext!).hasFocus, isFalse);
      Focus.of(focus2.currentContext!).requestFocus(); // Try to focus focus1
1611
      await tester.pump();
1612 1613
      expect(Focus.of(container1.currentContext!).hasFocus, isFalse);
      Focus.of(container1.currentContext!).requestFocus(); // Try to focus focus2
1614
      await tester.pump();
1615
      expect(Focus.of(container1.currentContext!).hasFocus, isFalse);
1616 1617
      await pumpTest();
      // Try again, now that we've set scope1's canRequestFocus to true again.
1618
      Focus.of(container1.currentContext!).requestFocus();
1619
      await tester.pump();
1620
      expect(Focus.of(container1.currentContext!).hasFocus, isTrue);
1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648
    });

    testWidgets('skipTraversal works as expected.', (WidgetTester tester) async {
      final FocusScopeNode scope1 = FocusScopeNode(debugLabel: 'scope1');
      final FocusScopeNode scope2 = FocusScopeNode(debugLabel: 'scope2');
      final FocusNode focus1 = FocusNode(debugLabel: 'focus1');
      final FocusNode focus2 = FocusNode(debugLabel: 'focus2');

      Future<void> pumpTest({
        bool traverseScope1 = false,
        bool traverseScope2 = false,
        bool traverseFocus1 = false,
        bool traverseFocus2 = false,
      }) async {
        await tester.pumpWidget(
          FocusScope(
            node: scope1,
            skipTraversal: traverseScope1,
            child: FocusScope(
              node: scope2,
              skipTraversal: traverseScope2,
              child: Focus(
                focusNode: focus1,
                skipTraversal: traverseFocus1,
                child: Focus(
                  focusNode: focus2,
                  skipTraversal: traverseFocus2,
                  child: Container(),
1649 1650 1651 1652
                ),
              ),
            ),
          ),
1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675
        );
        await tester.pump();
      }

      await pumpTest();
      expect(scope1.traversalDescendants, equals(<FocusNode>[focus2, focus1, scope2]));

      // Check childless node (focus2).
      await pumpTest(traverseFocus2: true);
      expect(scope1.traversalDescendants, equals(<FocusNode>[focus1, scope2]));

      // Check FocusNode with child (focus1). Shouldn't affect children.
      await pumpTest(traverseFocus1: true);
      expect(scope1.traversalDescendants, equals(<FocusNode>[focus2, scope2]));

      // Check FocusScopeNode with only FocusNode children (scope2). Should affect children.
      await pumpTest(traverseScope2: true);
      expect(scope1.traversalDescendants, equals(<FocusNode>[focus2, focus1]));

      // Check FocusScopeNode with both FocusNode children and FocusScope children (scope1). Should affect children.
      await pumpTest(traverseScope1: true);
      expect(scope1.traversalDescendants, equals(<FocusNode>[focus2, focus1, scope2]));
    });
1676

1677 1678 1679 1680
    testWidgets('descendantsAreFocusable works as expected.', (WidgetTester tester) async {
      final GlobalKey key1 = GlobalKey(debugLabel: '1');
      final GlobalKey key2 = GlobalKey(debugLabel: '2');
      final FocusNode focusNode = FocusNode();
1681
      bool? gotFocus;
1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692
      await tester.pumpWidget(
        Focus(
          descendantsAreFocusable: false,
          child: Focus(
            onFocusChange: (bool focused) => gotFocus = focused,
            child: Focus(
              key: key1,
              focusNode: focusNode,
              child: Container(key: key2),
            ),
          ),
1693 1694
        ),
      );
1695 1696

      final Element childWidget = tester.element(find.byKey(key1));
1697
      final FocusNode unfocusableNode = Focus.of(childWidget);
1698
      final Element containerWidget = tester.element(find.byKey(key2));
1699
      final FocusNode containerNode = Focus.of(containerWidget);
1700 1701 1702 1703 1704 1705 1706 1707 1708

      unfocusableNode.requestFocus();
      await tester.pump();

      expect(gotFocus, isNull);
      expect(containerNode.hasFocus, isFalse);
      expect(unfocusableNode.hasFocus, isFalse);

      containerNode.requestFocus();
1709 1710
      await tester.pump();

1711 1712 1713 1714
      expect(gotFocus, isNull);
      expect(containerNode.hasFocus, isFalse);
      expect(unfocusableNode.hasFocus, isFalse);
    });
1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748

    testWidgets('descendantsAreTraversable works as expected.', (WidgetTester tester) async {
      final FocusScopeNode scopeNode = FocusScopeNode(debugLabel: 'scope');
      final FocusNode node1 = FocusNode(debugLabel: 'node 1');
      final FocusNode node2 = FocusNode(debugLabel: 'node 2');
      final FocusNode node3 = FocusNode(debugLabel: 'node 3');

      await tester.pumpWidget(
        FocusScope(
          node: scopeNode,
          child: Column(
            children: <Widget>[
              Focus(
                focusNode: node1,
                child: Container(),
              ),
              Focus(
                focusNode: node2,
                descendantsAreTraversable: false,
                child: Focus(
                  focusNode: node3,
                  child: Container(),
                )
              ),
            ],
          ),
        ),
      );
      await tester.pump();

      expect(scopeNode.traversalDescendants, equals(<FocusNode>[node1, node2]));
      expect(node2.traversalDescendants, equals(<FocusNode>[]));
    });

1749 1750 1751 1752 1753 1754
    testWidgets("Focus doesn't introduce a Semantics node when includeSemantics is false", (WidgetTester tester) async {
      final SemanticsTester semantics = SemanticsTester(tester);
      await tester.pumpWidget(Focus(includeSemantics: false, child: Container()));
      final TestSemantics expectedSemantics = TestSemantics.root();
      expect(semantics, hasSemantics(expectedSemantics));
    });
1755

1756 1757 1758 1759
    testWidgets('Focus updates the onKey handler when the widget updates', (WidgetTester tester) async {
      final GlobalKey key1 = GlobalKey(debugLabel: '1');
      final FocusNode focusNode = FocusNode();
      bool? keyEventHandled;
1760
      KeyEventResult handleCallback(FocusNode node, RawKeyEvent event) {
1761 1762
        keyEventHandled = true;
        return KeyEventResult.handled;
1763 1764
      }
      KeyEventResult ignoreCallback(FocusNode node, RawKeyEvent event) => KeyEventResult.ignored;
1765 1766 1767 1768 1769 1770
      Focus focusWidget = Focus(
        onKey: ignoreCallback, // This one does nothing.
        focusNode: focusNode,
        skipTraversal: true,
        canRequestFocus: true,
        child: Container(key: key1),
1771
      );
1772 1773 1774 1775 1776 1777 1778 1779
      focusNode.onKeyEvent = null;
      await tester.pumpWidget(focusWidget);
      expect(focusNode.onKey, equals(ignoreCallback));
      expect(focusWidget.onKey, equals(focusNode.onKey));
      expect(focusWidget.onKeyEvent, equals(focusNode.onKeyEvent));
      expect(focusWidget.descendantsAreFocusable, equals(focusNode.descendantsAreFocusable));
      expect(focusWidget.skipTraversal, equals(focusNode.skipTraversal));
      expect(focusWidget.canRequestFocus, equals(focusNode.canRequestFocus));
1780 1781 1782 1783 1784 1785

      Focus.of(key1.currentContext!).requestFocus();
      await tester.pump();
      await tester.sendKeyEvent(LogicalKeyboardKey.enter);
      expect(keyEventHandled, isNull);

1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803
      focusWidget = Focus(
        onKey: handleCallback,
        focusNode: focusNode,
        skipTraversal: true,
        canRequestFocus: true,
        child: Container(key: key1),
      );
      await tester.pumpWidget(focusWidget);
      expect(focusNode.onKey, equals(handleCallback));
      expect(focusWidget.onKey, equals(focusNode.onKey));
      expect(focusWidget.onKeyEvent, equals(focusNode.onKeyEvent));
      expect(focusWidget.descendantsAreFocusable, equals(focusNode.descendantsAreFocusable));
      expect(focusWidget.skipTraversal, equals(focusNode.skipTraversal));
      expect(focusWidget.canRequestFocus, equals(focusNode.canRequestFocus));

      await tester.sendKeyEvent(LogicalKeyboardKey.enter);
      expect(keyEventHandled, isTrue);
    });
1804

1805 1806 1807 1808
    testWidgets('Focus updates the onKeyEvent handler when the widget updates', (WidgetTester tester) async {
      final GlobalKey key1 = GlobalKey(debugLabel: '1');
      final FocusNode focusNode = FocusNode();
      bool? keyEventHandled;
1809
      KeyEventResult handleEventCallback(FocusNode node, KeyEvent event) {
1810 1811
        keyEventHandled = true;
        return KeyEventResult.handled;
1812 1813
      }
      KeyEventResult ignoreEventCallback(FocusNode node, KeyEvent event) => KeyEventResult.ignored;
1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852
      Focus focusWidget = Focus(
        onKeyEvent: ignoreEventCallback, // This one does nothing.
        focusNode: focusNode,
        skipTraversal: true,
        canRequestFocus: true,
        child: Container(key: key1),
      );
      focusNode.onKeyEvent = null;
      await tester.pumpWidget(focusWidget);
      expect(focusNode.onKeyEvent, equals(ignoreEventCallback));
      expect(focusWidget.onKey, equals(focusNode.onKey));
      expect(focusWidget.onKeyEvent, equals(focusNode.onKeyEvent));
      expect(focusWidget.descendantsAreFocusable, equals(focusNode.descendantsAreFocusable));
      expect(focusWidget.skipTraversal, equals(focusNode.skipTraversal));
      expect(focusWidget.canRequestFocus, equals(focusNode.canRequestFocus));

      Focus.of(key1.currentContext!).requestFocus();
      await tester.pump();
      await tester.sendKeyEvent(LogicalKeyboardKey.enter);
      expect(keyEventHandled, isNull);

      focusWidget = Focus(
        onKeyEvent: handleEventCallback,
        focusNode: focusNode,
        skipTraversal: true,
        canRequestFocus: true,
        child: Container(key: key1),
      );
      await tester.pumpWidget(focusWidget);
      expect(focusNode.onKeyEvent, equals(handleEventCallback));
      expect(focusWidget.onKey, equals(focusNode.onKey));
      expect(focusWidget.onKeyEvent, equals(focusNode.onKeyEvent));
      expect(focusWidget.descendantsAreFocusable, equals(focusNode.descendantsAreFocusable));
      expect(focusWidget.skipTraversal, equals(focusNode.skipTraversal));
      expect(focusWidget.canRequestFocus, equals(focusNode.canRequestFocus));

      await tester.sendKeyEvent(LogicalKeyboardKey.enter);
      expect(keyEventHandled, isTrue);
    });
1853

1854 1855 1856 1857
    testWidgets("Focus doesn't update the focusNode attributes when the widget updates if withExternalFocusNode is used", (WidgetTester tester) async {
      final GlobalKey key1 = GlobalKey(debugLabel: '1');
      final FocusNode focusNode = FocusNode();
      bool? keyEventHandled;
1858
      KeyEventResult handleCallback(FocusNode node, RawKeyEvent event) {
1859 1860
        keyEventHandled = true;
        return KeyEventResult.handled;
1861 1862
      }
      KeyEventResult handleEventCallback(FocusNode node, KeyEvent event) {
1863 1864
        keyEventHandled = true;
        return KeyEventResult.handled;
1865 1866 1867
      }
      KeyEventResult ignoreCallback(FocusNode node, RawKeyEvent event) => KeyEventResult.ignored;
      KeyEventResult ignoreEventCallback(FocusNode node, KeyEvent event) => KeyEventResult.ignored;
1868 1869 1870
      focusNode.onKey = ignoreCallback;
      focusNode.onKeyEvent = ignoreEventCallback;
      focusNode.descendantsAreFocusable = false;
1871
      focusNode.descendantsAreTraversable = false;
1872 1873 1874 1875 1876 1877 1878 1879 1880 1881
      focusNode.skipTraversal = false;
      focusNode.canRequestFocus = true;
      Focus focusWidget = Focus.withExternalFocusNode(
        focusNode: focusNode,
        child: Container(key: key1),
      );
      await tester.pumpWidget(focusWidget);
      expect(focusNode.onKey, equals(ignoreCallback));
      expect(focusNode.onKeyEvent, equals(ignoreEventCallback));
      expect(focusNode.descendantsAreFocusable, isFalse);
1882
      expect(focusNode.descendantsAreTraversable, isFalse);
1883 1884 1885 1886 1887
      expect(focusNode.skipTraversal, isFalse);
      expect(focusNode.canRequestFocus, isTrue);
      expect(focusWidget.onKey, equals(focusNode.onKey));
      expect(focusWidget.onKeyEvent, equals(focusNode.onKeyEvent));
      expect(focusWidget.descendantsAreFocusable, equals(focusNode.descendantsAreFocusable));
1888
      expect(focusWidget.descendantsAreTraversable, equals(focusNode.descendantsAreTraversable));
1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899
      expect(focusWidget.skipTraversal, equals(focusNode.skipTraversal));
      expect(focusWidget.canRequestFocus, equals(focusNode.canRequestFocus));

      Focus.of(key1.currentContext!).requestFocus();
      await tester.pump();
      await tester.sendKeyEvent(LogicalKeyboardKey.enter);
      expect(keyEventHandled, isNull);

      focusNode.onKey = handleCallback;
      focusNode.onKeyEvent = handleEventCallback;
      focusNode.descendantsAreFocusable = true;
1900
      focusNode.descendantsAreTraversable = true;
1901 1902 1903
      focusWidget = Focus.withExternalFocusNode(
        focusNode: focusNode,
        child: Container(key: key1),
1904
      );
1905 1906 1907 1908
      await tester.pumpWidget(focusWidget);
      expect(focusNode.onKey, equals(handleCallback));
      expect(focusNode.onKeyEvent, equals(handleEventCallback));
      expect(focusNode.descendantsAreFocusable, isTrue);
1909
      expect(focusNode.descendantsAreTraversable, isTrue);
1910 1911 1912 1913 1914
      expect(focusNode.skipTraversal, isFalse);
      expect(focusNode.canRequestFocus, isTrue);
      expect(focusWidget.onKey, equals(focusNode.onKey));
      expect(focusWidget.onKeyEvent, equals(focusNode.onKeyEvent));
      expect(focusWidget.descendantsAreFocusable, equals(focusNode.descendantsAreFocusable));
1915
      expect(focusWidget.descendantsAreTraversable, equals(focusNode.descendantsAreTraversable));
1916 1917
      expect(focusWidget.skipTraversal, equals(focusNode.skipTraversal));
      expect(focusWidget.canRequestFocus, equals(focusNode.canRequestFocus));
1918 1919 1920 1921

      await tester.sendKeyEvent(LogicalKeyboardKey.enter);
      expect(keyEventHandled, isTrue);
    });
1922 1923 1924 1925 1926 1927 1928 1929

    testWidgets('Focus passes changes in attribute values to its focus node', (WidgetTester tester) async {
      await tester.pumpWidget(
        Focus(
          child: Container(),
        ),
      );
    });
1930
  });
1931

1932
  group('ExcludeFocus', () {
1933 1934 1935 1936
    testWidgets("Descendants of ExcludeFocus aren't focusable.", (WidgetTester tester) async {
      final GlobalKey key1 = GlobalKey(debugLabel: '1');
      final GlobalKey key2 = GlobalKey(debugLabel: '2');
      final FocusNode focusNode = FocusNode();
1937
      bool? gotFocus;
1938
      await tester.pumpWidget(
1939 1940 1941
        ExcludeFocus(
          child: Focus(
            onFocusChange: (bool focused) => gotFocus = focused,
1942
            child: Focus(
1943 1944 1945
              key: key1,
              focusNode: focusNode,
              child: Container(key: key2),
1946 1947 1948 1949 1950
            ),
          ),
        ),
      );

1951
      final Element childWidget = tester.element(find.byKey(key1));
1952
      final FocusNode unfocusableNode = Focus.of(childWidget);
1953
      final Element containerWidget = tester.element(find.byKey(key2));
1954
      final FocusNode containerNode = Focus.of(containerWidget);
1955

1956 1957
      unfocusableNode.requestFocus();
      await tester.pump();
1958

1959 1960 1961
      expect(gotFocus, isNull);
      expect(containerNode.hasFocus, isFalse);
      expect(unfocusableNode.hasFocus, isFalse);
1962

1963 1964
      containerNode.requestFocus();
      await tester.pump();
1965

1966 1967 1968 1969
      expect(gotFocus, isNull);
      expect(containerNode.hasFocus, isFalse);
      expect(unfocusableNode.hasFocus, isFalse);
    });
1970

1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037
    // Regression test for https://github.com/flutter/flutter/issues/61700
    testWidgets("ExcludeFocus doesn't transfer focus to another descendant.", (WidgetTester tester) async {
      final FocusNode parentFocusNode = FocusNode(debugLabel: 'group');
      final FocusNode focusNode1 = FocusNode(debugLabel: 'node 1');
      final FocusNode focusNode2 = FocusNode(debugLabel: 'node 2');
      await tester.pumpWidget(
        ExcludeFocus(
          excluding: false,
          child: Focus(
            focusNode: parentFocusNode,
            child: Column(
              children: <Widget>[
                Focus(
                  autofocus: true,
                  focusNode: focusNode1,
                  child: Container(),
                ),
                Focus(
                  focusNode: focusNode2,
                  child: Container(),
                ),
              ],
            ),
          ),
        ),
      );

      await tester.pump();

      expect(parentFocusNode.hasFocus, isTrue);
      expect(focusNode1.hasPrimaryFocus, isTrue);
      expect(focusNode2.hasFocus, isFalse);

      // Move focus to the second node to create some focus history for the scope.
      focusNode2.requestFocus();
      await tester.pump();

      expect(parentFocusNode.hasFocus, isTrue);
      expect(focusNode1.hasFocus, isFalse);
      expect(focusNode2.hasPrimaryFocus, isTrue);

      // Now turn off the focus for the subtree.
      await tester.pumpWidget(
        ExcludeFocus(
          child: Focus(
            focusNode: parentFocusNode,
            child: Column(
              children: <Widget>[
                Focus(
                  autofocus: true,
                  focusNode: focusNode1,
                  child: Container(),
                ),
                Focus(
                  focusNode: focusNode2,
                  child: Container(),
                ),
              ],
            ),
          ),
        ),
      );
      await tester.pump();

      expect(focusNode1.hasFocus, isFalse);
      expect(focusNode2.hasFocus, isFalse);
      expect(parentFocusNode.hasFocus, isFalse);
2038
      expect(parentFocusNode.enclosingScope!.hasPrimaryFocus, isTrue);
2039
    });
2040

2041 2042 2043 2044 2045 2046
    testWidgets("ExcludeFocus doesn't introduce a Semantics node", (WidgetTester tester) async {
      final SemanticsTester semantics = SemanticsTester(tester);
      await tester.pumpWidget(ExcludeFocus(child: Container()));
      final TestSemantics expectedSemantics = TestSemantics.root();
      expect(semantics, hasSemantics(expectedSemantics));
    });
2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077

    // Regression test for https://github.com/flutter/flutter/issues/92693
    testWidgets('Setting parent FocusScope.canRequestFocus to false, does not set descendant Focus._internalNode._canRequestFocus to false', (WidgetTester tester) async {
      final FocusNode childFocusNode = FocusNode(debugLabel: 'node 1');

      Widget buildFocusTree({required bool parentCanRequestFocus}) {
        return FocusScope(
          canRequestFocus: parentCanRequestFocus,
          child: Column(
            children: <Widget>[
              Focus(
                focusNode: childFocusNode,
                child: Container(),
              ),
            ],
          ),
        );
      }

      // childFocusNode.canRequestFocus is true when parent canRequestFocus is true
      await tester.pumpWidget(buildFocusTree(parentCanRequestFocus: true));
      expect(childFocusNode.canRequestFocus, isTrue);

      // childFocusNode.canRequestFocus is false when parent canRequestFocus is false
      await tester.pumpWidget(buildFocusTree(parentCanRequestFocus: false));
      expect(childFocusNode.canRequestFocus, isFalse);

      // childFocusNode.canRequestFocus is true again when parent canRequestFocus is changed back to true
      await tester.pumpWidget(buildFocusTree(parentCanRequestFocus: true));
      expect(childFocusNode.canRequestFocus, isTrue);
    });
2078
  });
2079
}
2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146

class TestFocus extends StatefulWidget {
  const TestFocus({
    super.key,
    this.debugLabel,
    this.name = 'a',
    this.autofocus = false,
    this.parentNode,
  });

  final String? debugLabel;
  final String name;
  final bool autofocus;
  final FocusNode? parentNode;

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

class TestFocusState extends State<TestFocus> {
  late FocusNode focusNode;
  late String _label;
  bool built = false;

  @override
  void dispose() {
    focusNode.removeListener(_updateLabel);
    focusNode.dispose();
    super.dispose();
  }

  String get label => focusNode.hasFocus ? '${widget.name.toUpperCase()} FOCUSED' : widget.name.toLowerCase();

  @override
  void initState() {
    super.initState();
    focusNode = FocusNode(debugLabel: widget.debugLabel);
    _label = label;
    focusNode.addListener(_updateLabel);
  }

  void _updateLabel() {
    setState(() {
      _label = label;
    });
  }

  @override
  Widget build(BuildContext context) {
    built = true;
    return GestureDetector(
      onTap: () {
        FocusScope.of(context).requestFocus(focusNode);
      },
      child: Focus(
        autofocus: widget.autofocus,
        focusNode: focusNode,
        parentNode: widget.parentNode,
        debugLabel: widget.debugLabel,
        child: Text(
          _label,
          textDirection: TextDirection.ltr,
        ),
      ),
    );
  }
}