focus_scope_test.dart 71.1 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 6 7
import 'dart:ui';

import 'package:flutter/semantics.dart';
8 9 10
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
11

12 13
import 'semantics_tester.dart';

14 15
class TestFocus extends StatefulWidget {
  const TestFocus({
16
    super.key,
17
    this.debugLabel,
18 19
    this.name = 'a',
    this.autofocus = false,
20
  });
21

22
  final String? debugLabel;
23 24 25 26
  final String name;
  final bool autofocus;

  @override
27
  TestFocusState createState() => TestFocusState();
28 29
}

30
class TestFocusState extends State<TestFocus> {
31 32
  late FocusNode focusNode;
  late String _label;
33
  bool built = false;
34 35 36

  @override
  void dispose() {
37
    focusNode.removeListener(_updateLabel);
38
    focusNode.dispose();
39 40 41
    super.dispose();
  }

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

44 45 46 47
  @override
  void initState() {
    super.initState();
    focusNode = FocusNode(debugLabel: widget.debugLabel);
48 49 50 51 52 53 54 55
    _label = label;
    focusNode.addListener(_updateLabel);
  }

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

58 59
  @override
  Widget build(BuildContext context) {
60
    built = true;
61 62 63 64
    return GestureDetector(
      onTap: () {
        FocusScope.of(context).requestFocus(focusNode);
      },
65 66 67 68 69 70 71 72
      child: Focus(
        autofocus: widget.autofocus,
        focusNode: focusNode,
        debugLabel: widget.debugLabel,
        child: Text(
          _label,
          textDirection: TextDirection.ltr,
        ),
73 74 75 76 77 78
      ),
    );
  }
}

void main() {
79
  group('FocusScope', () {
80 81
    testWidgets('Can focus', (WidgetTester tester) async {
      final GlobalKey<TestFocusState> key = GlobalKey();
82

83
      await tester.pumpWidget(
84
        TestFocus(key: key),
85
      );
86

87
      expect(key.currentState!.focusNode.hasFocus, isFalse);
88

89
      FocusScope.of(key.currentContext!).requestFocus(key.currentState!.focusNode);
90
      await tester.pumpAndSettle();
91

92
      expect(key.currentState!.focusNode.hasFocus, isTrue);
93 94
      expect(find.text('A FOCUSED'), findsOneWidget);
    });
95

96 97 98 99 100
    testWidgets('Can unfocus', (WidgetTester tester) async {
      final GlobalKey<TestFocusState> keyA = GlobalKey();
      final GlobalKey<TestFocusState> keyB = GlobalKey();
      await tester.pumpWidget(
        Column(
101
          children: <Widget>[
102
            TestFocus(key: keyA),
103
            TestFocus(key: keyB, name: 'b'),
104
          ],
105
        ),
106
      );
107

108
      expect(keyA.currentState!.focusNode.hasFocus, isFalse);
109
      expect(find.text('a'), findsOneWidget);
110
      expect(keyB.currentState!.focusNode.hasFocus, isFalse);
111
      expect(find.text('b'), findsOneWidget);
112

113
      FocusScope.of(keyA.currentContext!).requestFocus(keyA.currentState!.focusNode);
114
      await tester.pumpAndSettle();
115

116
      expect(keyA.currentState!.focusNode.hasFocus, isTrue);
117
      expect(find.text('A FOCUSED'), findsOneWidget);
118
      expect(keyB.currentState!.focusNode.hasFocus, isFalse);
119
      expect(find.text('b'), findsOneWidget);
120

121
      // Set focus to the "B" node to unfocus the "A" node.
122
      FocusScope.of(keyB.currentContext!).requestFocus(keyB.currentState!.focusNode);
123
      await tester.pumpAndSettle();
124

125
      expect(keyA.currentState!.focusNode.hasFocus, isFalse);
126
      expect(find.text('a'), findsOneWidget);
127
      expect(keyB.currentState!.focusNode.hasFocus, isTrue);
128 129
      expect(find.text('B FOCUSED'), findsOneWidget);
    });
130

131 132 133 134 135 136
    testWidgets('Autofocus works', (WidgetTester tester) async {
      final GlobalKey<TestFocusState> keyA = GlobalKey();
      final GlobalKey<TestFocusState> keyB = GlobalKey();
      await tester.pumpWidget(
        Column(
          children: <Widget>[
137
            TestFocus(key: keyA),
138 139 140 141 142 143 144
            TestFocus(key: keyB, name: 'b', autofocus: true),
          ],
        ),
      );

      await tester.pump();

145
      expect(keyA.currentState!.focusNode.hasFocus, isFalse);
146
      expect(find.text('a'), findsOneWidget);
147
      expect(keyB.currentState!.focusNode.hasFocus, isTrue);
148 149 150
      expect(find.text('B FOCUSED'), findsOneWidget);
    });

151 152 153 154 155 156
    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(
157
          children: <Widget>[
158 159 160 161 162 163 164
            TestFocus(
              key: keyA,
              autofocus: true,
            ),
            TestFocus(
              key: keyB,
              name: 'b',
165 166 167
            ),
          ],
        ),
168 169 170 171
      );

      // Autofocus is delayed one frame.
      await tester.pump();
172
      expect(keyA.currentState!.focusNode.hasFocus, isTrue);
173
      expect(find.text('A FOCUSED'), findsOneWidget);
174
      expect(keyB.currentState!.focusNode.hasFocus, isFalse);
175 176 177
      expect(find.text('b'), findsOneWidget);
      await tester.tap(find.text('A FOCUSED'));
      await tester.pump();
178
      expect(keyA.currentState!.focusNode.hasFocus, isTrue);
179
      expect(find.text('A FOCUSED'), findsOneWidget);
180
      expect(keyB.currentState!.focusNode.hasFocus, isFalse);
181 182 183
      expect(find.text('b'), findsOneWidget);
      await tester.tap(find.text('b'));
      await tester.pump();
184
      expect(keyA.currentState!.focusNode.hasFocus, isFalse);
185
      expect(find.text('a'), findsOneWidget);
186
      expect(keyB.currentState!.focusNode.hasFocus, isTrue);
187 188 189
      expect(find.text('B FOCUSED'), findsOneWidget);
      await tester.tap(find.text('a'));
      await tester.pump();
190
      expect(keyA.currentState!.focusNode.hasFocus, isTrue);
191
      expect(find.text('A FOCUSED'), findsOneWidget);
192
      expect(keyB.currentState!.focusNode.hasFocus, isFalse);
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
      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',
              ),
            ],
          ),
        ),
      );

220
      expect(key.currentState!.focusNode.hasFocus, isFalse);
221
      expect(find.text('a'), findsOneWidget);
222
      FocusScope.of(key.currentContext!).requestFocus(key.currentState!.focusNode);
223 224
      await tester.pumpAndSettle();

225
      expect(key.currentState!.focusNode.hasFocus, isTrue);
226 227 228 229 230
      expect(find.text('A FOCUSED'), findsOneWidget);

      expect(parentFocusScope, hasAGoodToStringDeep);
      expect(
        parentFocusScope.toStringDeep(),
231 232 233 234 235 236 237 238 239 240
        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',
        ),
241 242
      );

243
      expect(FocusManager.instance.rootScope, hasAGoodToStringDeep);
244
      expect(
245
        FocusManager.instance.rootScope.toStringDeep(minLevel: DiagnosticLevel.info),
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
        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',
        ),
261 262 263
      );

      // Add the child focus scope to the focus tree.
264
      final FocusAttachment childAttachment = childFocusScope.attach(key.currentContext);
265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
      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(),
              ),
            ],
          ),
        ),
      );

290
      expect(key.currentState!.focusNode.hasFocus, isFalse);
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314
      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();

315
      expect(key.currentState!.focusNode.hasFocus, isFalse);
316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332
      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',
              ),
            ],
          ),
        ),
      );
333

334
      await tester.pumpAndSettle();
335
      expect(key.currentState!.focusNode.hasFocus, isFalse);
336
      expect(find.text('a'), findsOneWidget);
337

338 339 340 341 342
      // Must detach the child because we had to attach it in order to call
      // setFirstFocus before adding to the widget.
      childAttachment.detach();
    });

343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390
    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();

391
      expect(keyA.currentState!.focusNode.hasFocus, isTrue);
392 393 394 395 396
      expect(find.text('A FOCUSED'), findsOneWidget);

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

397
      expect(keyA.currentState!.focusNode.hasFocus, isFalse);
398 399 400 401 402
      expect(find.text('a'), findsOneWidget);

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

403
      expect(keyA.currentState!.focusNode.hasFocus, isTrue);
404 405
      expect(find.text('A FOCUSED'), findsOneWidget);

406
      keyB.currentState!.focusNode.requestFocus();
407 408
      await tester.pumpAndSettle();

409
      expect(keyB.currentState!.focusNode.hasFocus, isTrue);
410 411 412 413 414 415 416
      expect(find.text('B FOCUSED'), findsOneWidget);
      expect(parentFocusScope.isFirstFocus, isTrue);
      expect(childFocusScope1.isFirstFocus, isTrue);

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

417
      expect(keyB.currentState!.focusNode.hasFocus, isFalse);
418 419 420 421 422
      expect(find.text('b'), findsOneWidget);
      expect(parentFocusScope.isFirstFocus, isTrue);
      expect(childFocusScope1.isFirstFocus, isFalse);
      expect(childFocusScope2.isFirstFocus, isTrue);

423
      keyC.currentState!.focusNode.requestFocus();
424 425
      await tester.pumpAndSettle();

426
      expect(keyB.currentState!.focusNode.hasFocus, isFalse);
427
      expect(find.text('b'), findsOneWidget);
428
      expect(keyC.currentState!.focusNode.hasFocus, isTrue);
429 430 431 432 433 434 435
      expect(find.text('C FOCUSED'), findsOneWidget);
      expect(parentFocusScope.isFirstFocus, isTrue);
      expect(childFocusScope1.isFirstFocus, isFalse);
      expect(childFocusScope2.isFirstFocus, isTrue);

      childFocusScope1.requestFocus();
      await tester.pumpAndSettle();
436
      expect(keyB.currentState!.focusNode.hasFocus, isTrue);
437
      expect(find.text('B FOCUSED'), findsOneWidget);
438
      expect(keyC.currentState!.focusNode.hasFocus, isFalse);
439 440 441 442 443 444 445
      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 {
446 447 448 449 450
      final GlobalKey<TestFocusState> keyA = GlobalKey();
      final GlobalKey<TestFocusState> keyB = GlobalKey();

      await tester.pumpWidget(
        Column(
451
          children: <Widget>[
452 453 454 455 456 457
            TestFocus(
              key: keyA,
            ),
            TestFocus(
              key: keyB,
              name: 'b',
458 459 460
            ),
          ],
        ),
461
      );
462

463
      FocusScope.of(keyA.currentContext!).requestFocus(keyA.currentState!.focusNode);
464

465
      await tester.pumpAndSettle();
466

467
      expect(keyA.currentState!.focusNode.hasFocus, isTrue);
468
      expect(find.text('A FOCUSED'), findsOneWidget);
469
      expect(keyB.currentState!.focusNode.hasFocus, isFalse);
470 471 472 473
      expect(find.text('b'), findsOneWidget);

      await tester.pumpWidget(
        Column(
474
          children: <Widget>[
475 476 477 478
            TestFocus(
              key: keyB,
              name: 'b',
            ),
479 480
          ],
        ),
481
      );
482

483
      await tester.pump();
484

485
      expect(keyB.currentState!.focusNode.hasFocus, isFalse);
486 487
      expect(find.text('b'), findsOneWidget);
    });
488

489 490 491 492
    testWidgets('Adding a new FocusScope attaches the child it to its parent.', (WidgetTester tester) async {
      final GlobalKey<TestFocusState> keyA = GlobalKey();
      final FocusScopeNode parentFocusScope = FocusScopeNode(debugLabel: 'Parent Scope Node');
      final FocusScopeNode childFocusScope = FocusScopeNode(debugLabel: 'Child Scope Node');
493

494 495 496 497 498
      await tester.pumpWidget(
        FocusScope(
          node: childFocusScope,
          child: TestFocus(
            debugLabel: 'Child',
499
            key: keyA,
500
          ),
501 502
        ),
      );
503

504 505 506 507
      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!));
508

509
      await tester.pumpAndSettle();
510

511
      expect(keyA.currentState!.focusNode.hasFocus, isTrue);
512 513
      expect(find.text('A FOCUSED'), findsOneWidget);
      expect(childFocusScope.isFirstFocus, isTrue);
514

515 516 517 518 519 520 521 522 523
      await tester.pumpWidget(
        FocusScope(
          node: parentFocusScope,
          child: FocusScope(
            node: childFocusScope,
            child: TestFocus(
              debugLabel: 'Child',
              key: keyA,
            ),
524
          ),
525 526 527 528 529 530
        ),
      );

      await tester.pump();
      expect(childFocusScope.isFirstFocus, isTrue);
      // Node keeps it's focus when moved to the new scope.
531
      expect(keyA.currentState!.focusNode.hasFocus, isTrue);
532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561
      expect(find.text('A FOCUSED'), findsOneWidget);
    });

    // 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',
              ),
            ],
          ),
        ),
      );

562 563
      FocusScope.of(keyA.currentContext!).requestFocus(keyA.currentState!.focusNode);
      final FocusScopeNode scope = FocusScope.of(keyA.currentContext!);
564
      FocusManager.instance.rootScope.setFirstFocus(scope);
565 566 567

      await tester.pumpAndSettle();

568
      expect(keyA.currentState!.focusNode.hasFocus, isTrue);
569
      expect(find.text('A FOCUSED'), findsOneWidget);
570
      expect(keyB.currentState!.focusNode.hasFocus, isFalse);
571 572 573 574 575 576 577 578 579 580 581 582 583 584 585
      expect(find.text('b'), findsOneWidget);

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

587
      await tester.pump();
588

589
      expect(keyB.currentState!.focusNode.hasFocus, isFalse);
590 591
      expect(find.text('b'), findsOneWidget);
    });
592

593 594 595 596 597 598
    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');
599

600 601 602
      // This checks both FocusScopes that have their own nodes, as well as those
      // that use external nodes.
      await tester.pumpWidget(
603
        FocusTraversalGroup(
604 605 606 607 608 609 610 611 612 613 614 615 616
          child: Column(
            children: <Widget>[
              FocusScope(
                key: scopeKeyA,
                node: parentFocusScope,
                child: Column(
                  children: <Widget>[
                    TestFocus(
                      debugLabel: 'Child A',
                      key: keyA,
                    ),
                  ],
                ),
617
              ),
618 619 620 621 622 623 624 625 626 627 628
              FocusScope(
                key: scopeKeyB,
                child: Column(
                  children: <Widget>[
                    TestFocus(
                      debugLabel: 'Child B',
                      key: keyB,
                      name: 'b',
                    ),
                  ],
                ),
629
              ),
630 631
            ],
          ),
632
        ),
633
      );
634

635 636 637 638
      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!);
639 640
      FocusManager.instance.rootScope.setFirstFocus(bScope);
      FocusManager.instance.rootScope.setFirstFocus(aScope);
641

642
      await tester.pumpAndSettle();
643

644 645
      expect(FocusScope.of(keyA.currentContext!).isFirstFocus, isTrue);
      expect(keyA.currentState!.focusNode.hasFocus, isTrue);
646
      expect(find.text('A FOCUSED'), findsOneWidget);
647
      expect(keyB.currentState!.focusNode.hasFocus, isFalse);
648
      expect(find.text('b'), findsOneWidget);
649

650
      await tester.pumpWidget(Container());
651

652
      expect(FocusManager.instance.rootScope.children, isEmpty);
653
    });
654

655 656 657 658 659 660 661 662 663 664
    // 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(
665
        FocusTraversalGroup(
666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697
          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',
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      );

698 699 700 701
      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!);
702 703
      FocusManager.instance.rootScope.setFirstFocus(bScope);
      FocusManager.instance.rootScope.setFirstFocus(aScope);
704 705 706

      await tester.pumpAndSettle();

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

      await tester.pumpWidget(
714
        FocusTraversalGroup(
715 716 717 718 719 720 721 722
          child: Column(
            children: <Widget>[
              FocusScope(
                key: scopeKeyB,
                node: parentFocusScope2,
                child: Column(
                  children: <Widget>[
                    TestFocus(
723
                      debugLabel: 'Child B',
724 725 726 727 728 729 730 731 732 733 734 735 736 737
                      key: keyB,
                      name: 'b',
                      autofocus: true,
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      );

      await tester.pump();

738
      expect(keyB.currentState!.focusNode.hasFocus, isTrue);
739
      expect(find.text('B FOCUSED'), findsOneWidget);
740 741
    });

742 743 744 745 746
    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');
747

748
      await tester.pumpWidget(
749
        FocusTraversalGroup(
750 751 752 753 754 755 756 757 758 759 760 761
          child: Column(
            children: <Widget>[
              FocusScope(
                node: parentFocusScope1,
                child: Column(
                  children: <Widget>[
                    TestFocus(
                      debugLabel: 'Child A',
                      key: keyA,
                    ),
                  ],
                ),
762
              ),
763 764 765 766 767 768 769 770 771 772 773
              FocusScope(
                node: parentFocusScope2,
                child: Column(
                  children: <Widget>[
                    TestFocus(
                      debugLabel: 'Child B',
                      key: keyB,
                      name: 'b',
                    ),
                  ],
                ),
774
              ),
775 776
            ],
          ),
777
        ),
778 779
      );

780 781 782 783
      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!);
784 785
      FocusManager.instance.rootScope.setFirstFocus(bScope);
      FocusManager.instance.rootScope.setFirstFocus(aScope);
786 787 788

      await tester.pumpAndSettle();

789 790
      expect(FocusScope.of(keyA.currentContext!).isFirstFocus, isTrue);
      expect(keyA.currentState!.focusNode.hasFocus, isTrue);
791
      expect(find.text('A FOCUSED'), findsOneWidget);
792
      expect(keyB.currentState!.focusNode.hasFocus, isFalse);
793 794 795
      expect(find.text('b'), findsOneWidget);

      await tester.pumpWidget(
796
        FocusTraversalGroup(
797 798 799 800 801 802 803
          child: Column(
            children: <Widget>[
              FocusScope(
                node: parentFocusScope2,
                child: Column(
                  children: <Widget>[
                    TestFocus(
804
                      debugLabel: 'Child B',
805 806 807 808 809 810
                      key: keyB,
                      name: 'b',
                      autofocus: true,
                    ),
                  ],
                ),
811
              ),
812 813
            ],
          ),
814
        ),
815 816
      );
      await tester.pump();
817

818
      expect(keyB.currentState!.focusNode.hasFocus, isTrue);
819
      expect(find.text('B FOCUSED'), findsOneWidget);
820
    });
821

822 823 824 825 826
    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();
827

828 829 830 831 832 833 834 835 836 837 838 839
      await tester.pumpWidget(
        Column(
          children: <Widget>[
            FocusScope(
              node: parentFocusScope1,
              child: Column(
                children: <Widget>[
                  TestFocus(
                    key: keyA,
                  ),
                ],
              ),
840
            ),
841 842 843 844 845 846 847 848 849 850
            FocusScope(
              node: parentFocusScope2,
              child: Column(
                children: <Widget>[
                  TestFocus(
                    key: keyB,
                    name: 'b',
                  ),
                ],
              ),
851
            ),
852 853 854
          ],
        ),
      );
855

856 857
      FocusScope.of(keyA.currentContext!).requestFocus(keyA.currentState!.focusNode);
      final FocusScopeNode aScope = FocusScope.of(keyA.currentContext!);
858
      FocusManager.instance.rootScope.setFirstFocus(aScope);
859

860
      await tester.pumpAndSettle();
861

862
      expect(keyA.currentState!.focusNode.hasFocus, isTrue);
863
      expect(find.text('A FOCUSED'), findsOneWidget);
864
      expect(keyB.currentState!.focusNode.hasFocus, isFalse);
865
      expect(find.text('b'), findsOneWidget);
866

867 868 869 870 871 872 873 874 875 876 877 878 879
      await tester.pumpWidget(
        Column(
          children: <Widget>[
            FocusScope(
              node: parentFocusScope1,
              child: Column(
                children: <Widget>[
                  TestFocus(
                    key: keyB,
                    name: 'b',
                  ),
                ],
              ),
880
            ),
881 882 883 884 885 886 887 888 889 890 891 892 893
            FocusScope(
              node: parentFocusScope2,
              child: Column(
                children: <Widget>[
                  TestFocus(
                    key: keyA,
                  ),
                ],
              ),
            ),
          ],
        ),
      );
894

895
      await tester.pump();
896

897
      expect(keyA.currentState!.focusNode.hasFocus, isTrue);
898
      expect(find.text('A FOCUSED'), findsOneWidget);
899
      expect(keyB.currentState!.focusNode.hasFocus, isFalse);
900 901
      expect(find.text('b'), findsOneWidget);
    });
902

903 904 905 906 907
    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();
908

909 910 911 912 913 914 915 916 917 918 919 920 921
      await tester.pumpWidget(
        Column(
          children: <Widget>[
            FocusScope(
              node: parentFocusScope1,
              child: Column(
                children: <Widget>[
                  TestFocus(
                    debugLabel: 'Child A',
                    key: keyA,
                  ),
                ],
              ),
922
            ),
923 924 925 926 927 928 929 930 931 932 933
            FocusScope(
              node: parentFocusScope2,
              child: Column(
                children: <Widget>[
                  TestFocus(
                    debugLabel: 'Child B',
                    key: keyB,
                    name: 'b',
                  ),
                ],
              ),
934
            ),
935 936 937
          ],
        ),
      );
938

939 940
      FocusScope.of(keyA.currentContext!).requestFocus(keyA.currentState!.focusNode);
      final FocusScopeNode aScope = FocusScope.of(keyA.currentContext!);
941
      FocusManager.instance.rootScope.setFirstFocus(aScope);
942

943
      await tester.pumpAndSettle();
944

945
      expect(keyA.currentState!.focusNode.hasFocus, isTrue);
946
      expect(find.text('A FOCUSED'), findsOneWidget);
947
      expect(keyB.currentState!.focusNode.hasFocus, isFalse);
948
      expect(find.text('b'), findsOneWidget);
949

950 951 952 953 954 955 956 957 958 959 960 961 962 963
      // 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,
                  ),
                ],
              ),
964
            ),
965 966 967 968 969 970 971 972 973 974 975 976 977 978 979
            FocusScope(
              node: parentFocusScope1,
              child: Column(
                children: <Widget>[
                  TestFocus(
                    debugLabel: 'Child B',
                    key: keyB,
                    name: 'b',
                  ),
                ],
              ),
            ),
          ],
        ),
      );
980

981
      await tester.pump();
982

983
      expect(keyA.currentState!.focusNode.hasFocus, isTrue);
984
      expect(find.text('A FOCUSED'), findsOneWidget);
985
      expect(keyB.currentState!.focusNode.hasFocus, isFalse);
986 987
      expect(find.text('b'), findsOneWidget);
    });
988

989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004
    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);
1005
      expect(rootNode, equals(firstElement.owner!.focusManager.rootScope));
1006
    });
1007

1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030
    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);
    });
1031

1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069
    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);
    });
1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087

    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;
1088
      focusScopeNode.descendantsAreTraversable = false;
1089 1090 1091 1092 1093 1094 1095 1096 1097 1098
      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);
1099
      expect(focusScopeNode.descendantsAreTraversable, isFalse);
1100 1101 1102 1103 1104
      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));
1105
      expect(focusScopeWidget.descendantsAreTraversable, equals(focusScopeNode.descendantsAreTraversable));
1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116
      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;
1117
      focusScopeNode.descendantsAreTraversable = true;
1118 1119 1120 1121 1122 1123 1124 1125
      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);
1126
      expect(focusScopeNode.descendantsAreTraversable, isTrue);
1127 1128 1129 1130 1131
      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));
1132
      expect(focusScopeWidget.descendantsAreTraversable, equals(focusScopeNode.descendantsAreTraversable));
1133 1134 1135 1136 1137 1138
      expect(focusScopeWidget.skipTraversal, equals(focusScopeNode.skipTraversal));
      expect(focusScopeWidget.canRequestFocus, equals(focusScopeNode.canRequestFocus));

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

1141
  group('Focus', () {
1142
    testWidgets('Focus.of stops at the nearest Focus widget.', (WidgetTester tester) async {
1143 1144 1145 1146 1147 1148
      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');
1149
      final FocusScopeNode scopeNode = FocusScopeNode();
1150
      await tester.pumpWidget(
1151
        FocusScope(
1152
          key: key1,
1153
          node: scopeNode,
1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167
          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,
                  ),
1168
                ),
1169
              ),
1170 1171
            ),
          ),
1172 1173 1174 1175 1176 1177 1178 1179
        ),
      );
      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));
1180
      final FocusNode root = element1.owner!.focusManager.rootScope;
1181

1182 1183 1184 1185 1186 1187
      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));
1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204
    });
    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,
1205 1206 1207
                child: Focus(
                  key: key3,
                  child: Container(),
1208
                ),
1209 1210 1211
              ),
              Focus(
                key: key4,
1212 1213 1214
                child: Focus(
                  key: key5,
                  child: Container(),
1215
                ),
1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229
              ),
              Focus(
                key: key6,
                child: Column(
                  children: <Widget>[
                    Focus(
                      key: key7,
                      child: Container(),
                    ),
                    Focus(
                      key: key8,
                      child: Container(),
                    ),
                  ],
1230
                ),
1231 1232
              ),
            ],
1233
          ),
1234 1235 1236 1237 1238 1239 1240 1241
        ),
      );

      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);
1242
        keys.add(node.context!.widget.key!);
1243 1244 1245 1246 1247
        return true;
      }

      await tester.pump();

1248
      Focus.of(firstScope).descendants.forEach(visitor);
1249 1250 1251 1252 1253 1254 1255 1256 1257
      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();
1258
      Focus.of(secondScope).descendants.forEach(visitor);
1259 1260 1261
      expect(nodes.length, equals(2));
      expect(keys, equals(<Key>[key7, key8]));
    });
1262

1263 1264
    testWidgets('Can set focus.', (WidgetTester tester) async {
      final GlobalKey key1 = GlobalKey(debugLabel: '1');
1265
      late bool gotFocus;
1266 1267 1268 1269 1270 1271 1272 1273
      await tester.pumpWidget(
        Focus(
          onFocusChange: (bool focused) => gotFocus = focused,
          child: Container(key: key1),
        ),
      );

      final Element firstNode = tester.element(find.byKey(key1));
1274
      final FocusNode node = Focus.of(firstNode);
1275 1276 1277 1278 1279 1280 1281
      node.requestFocus();

      await tester.pump();

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

1283 1284
    testWidgets('Focus is ignored when set to not focusable.', (WidgetTester tester) async {
      final GlobalKey key1 = GlobalKey(debugLabel: '1');
1285
      bool? gotFocus;
1286 1287 1288 1289 1290 1291 1292 1293 1294
      await tester.pumpWidget(
        Focus(
          canRequestFocus: false,
          onFocusChange: (bool focused) => gotFocus = focused,
          child: Container(key: key1),
        ),
      );

      final Element firstNode = tester.element(find.byKey(key1));
1295
      final FocusNode node = Focus.of(firstNode);
1296 1297 1298 1299 1300 1301 1302
      node.requestFocus();

      await tester.pump();

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

1304 1305
    testWidgets('Focus is lost when set to not focusable.', (WidgetTester tester) async {
      final GlobalKey key1 = GlobalKey(debugLabel: '1');
1306
      bool? gotFocus;
1307 1308 1309 1310 1311 1312 1313 1314 1315 1316
      await tester.pumpWidget(
        Focus(
          autofocus: true,
          canRequestFocus: true,
          onFocusChange: (bool focused) => gotFocus = focused,
          child: Container(key: key1),
        ),
      );

      Element firstNode = tester.element(find.byKey(key1));
1317
      FocusNode node = Focus.of(firstNode);
1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334
      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));
1335
      node = Focus.of(firstNode);
1336 1337 1338 1339 1340 1341 1342
      node.requestFocus();

      await tester.pump();

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

1344 1345 1346 1347
    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();
1348
      bool? gotFocus;
1349 1350 1351 1352 1353 1354 1355 1356 1357
      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));
1358
      final FocusNode unfocusableNode = Focus.of(childWidget);
1359 1360 1361 1362 1363 1364 1365 1366
      unfocusableNode.requestFocus();

      await tester.pump();

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

      final Element containerWidget = tester.element(find.byKey(key2));
1367
      final FocusNode focusableNode = Focus.of(containerWidget);
1368 1369 1370 1371 1372 1373 1374
      focusableNode.requestFocus();

      await tester.pump();

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

1376 1377
    testWidgets('Nodes are removed when all Focuses are removed.', (WidgetTester tester) async {
      final GlobalKey key1 = GlobalKey(debugLabel: '1');
1378
      late bool gotFocus;
1379 1380 1381 1382 1383 1384 1385 1386
      await tester.pumpWidget(
        FocusScope(
          child: Focus(
            onFocusChange: (bool focused) => gotFocus = focused,
            child: Container(key: key1),
          ),
        ),
      );
1387

1388
      final Element firstNode = tester.element(find.byKey(key1));
1389
      final FocusNode node = Focus.of(firstNode);
1390
      node.requestFocus();
1391

1392
      await tester.pump();
1393

1394 1395
      expect(gotFocus, isTrue);
      expect(node.hasFocus, isTrue);
1396

1397
      await tester.pumpWidget(Container());
1398

1399 1400
      expect(FocusManager.instance.rootScope.descendants, isEmpty);
    });
1401

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

1405
      await tester.pumpWidget(
1406
        TestFocus(key: key),
1407
      );
1408

1409
      final SemanticsNode semantics = tester.getSemantics(find.byKey(key));
1410

1411
      expect(key.currentState!.focusNode.hasFocus, isFalse);
1412 1413
      expect(semantics.hasFlag(SemanticsFlag.isFocused), isFalse);
      expect(semantics.hasFlag(SemanticsFlag.isFocusable), isTrue);
1414

1415
      FocusScope.of(key.currentContext!).requestFocus(key.currentState!.focusNode);
1416
      await tester.pumpAndSettle();
1417

1418
      expect(key.currentState!.focusNode.hasFocus, isTrue);
1419 1420
      expect(semantics.hasFlag(SemanticsFlag.isFocused), isTrue);
      expect(semantics.hasFlag(SemanticsFlag.isFocusable), isTrue);
1421

1422
      key.currentState!.focusNode.canRequestFocus = false;
1423
      await tester.pumpAndSettle();
1424

1425 1426
      expect(key.currentState!.focusNode.hasFocus, isFalse);
      expect(key.currentState!.focusNode.canRequestFocus, isFalse);
1427 1428 1429
      expect(semantics.hasFlag(SemanticsFlag.isFocused), isFalse);
      expect(semantics.hasFlag(SemanticsFlag.isFocusable), isFalse);
    });
1430

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

1434
      final TestFocus testFocus = TestFocus(key: key);
1435
      await tester.pumpWidget(
1436 1437 1438 1439
        testFocus,
      );

      await tester.pumpAndSettle();
1440 1441
      key.currentState!.built = false;
      key.currentState!.focusNode.canRequestFocus = false;
1442
      await tester.pumpAndSettle();
1443
      key.currentState!.built = true;
1444

1445
      expect(key.currentState!.focusNode.canRequestFocus, isFalse);
1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466
    });

    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,
1467
              child: Focus(
1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485
                key: focus1,
                canRequestFocus: allowFocus1,
                child: Focus(
                  key: focus2,
                  canRequestFocus: allowFocus2,
                  child: Container(
                    key: container1,
                  ),
                ),
              ),
            ),
          ),
        );
        await tester.pump();
      }

      // Check childless node (focus2).
      await pumpTest();
1486
      Focus.of(container1.currentContext!).requestFocus();
1487
      await tester.pump();
1488
      expect(Focus.of(container1.currentContext!).hasFocus, isTrue);
1489
      await pumpTest(allowFocus2: false);
1490 1491
      expect(Focus.of(container1.currentContext!).hasFocus, isFalse);
      Focus.of(container1.currentContext!).requestFocus();
1492
      await tester.pump();
1493
      expect(Focus.of(container1.currentContext!).hasFocus, isFalse);
1494
      await pumpTest();
1495
      Focus.of(container1.currentContext!).requestFocus();
1496
      await tester.pump();
1497
      expect(Focus.of(container1.currentContext!).hasFocus, isTrue);
1498 1499 1500

      // Check FocusNode with child (focus1). Shouldn't affect children.
      await pumpTest(allowFocus1: false);
1501 1502
      expect(Focus.of(container1.currentContext!).hasFocus, isTrue); // focus2 has focus.
      Focus.of(focus2.currentContext!).requestFocus(); // Try to focus focus1
1503
      await tester.pump();
1504 1505
      expect(Focus.of(container1.currentContext!).hasFocus, isTrue); // focus2 still has focus.
      Focus.of(container1.currentContext!).requestFocus(); // Now try to focus focus2
1506
      await tester.pump();
1507
      expect(Focus.of(container1.currentContext!).hasFocus, isTrue);
1508 1509
      await pumpTest();
      // Try again, now that we've set focus1's canRequestFocus to true again.
1510
      Focus.of(container1.currentContext!).unfocus();
1511
      await tester.pump();
1512 1513
      expect(Focus.of(container1.currentContext!).hasFocus, isFalse);
      Focus.of(container1.currentContext!).requestFocus();
1514
      await tester.pump();
1515
      expect(Focus.of(container1.currentContext!).hasFocus, isTrue);
1516 1517 1518

      // Check FocusScopeNode with only FocusNode children (scope2). Should affect children.
      await pumpTest(allowScope2: false);
1519
      expect(Focus.of(container1.currentContext!).hasFocus, isFalse);
1520
      FocusScope.of(focus1.currentContext!).requestFocus(); // Try to focus scope2
1521
      await tester.pump();
1522 1523
      expect(Focus.of(container1.currentContext!).hasFocus, isFalse);
      Focus.of(focus2.currentContext!).requestFocus(); // Try to focus focus1
1524
      await tester.pump();
1525 1526
      expect(Focus.of(container1.currentContext!).hasFocus, isFalse);
      Focus.of(container1.currentContext!).requestFocus(); // Try to focus focus2
1527
      await tester.pump();
1528
      expect(Focus.of(container1.currentContext!).hasFocus, isFalse);
1529 1530
      await pumpTest();
      // Try again, now that we've set scope2's canRequestFocus to true again.
1531
      Focus.of(container1.currentContext!).requestFocus();
1532
      await tester.pump();
1533
      expect(Focus.of(container1.currentContext!).hasFocus, isTrue);
1534 1535 1536

      // Check FocusScopeNode with both FocusNode children and FocusScope children (scope1). Should affect children.
      await pumpTest(allowScope1: false);
1537
      expect(Focus.of(container1.currentContext!).hasFocus, isFalse);
1538
      FocusScope.of(scope2.currentContext!).requestFocus(); // Try to focus scope1
1539
      await tester.pump();
1540
      expect(Focus.of(container1.currentContext!).hasFocus, isFalse);
1541
      FocusScope.of(focus1.currentContext!).requestFocus(); // Try to focus scope2
1542
      await tester.pump();
1543 1544
      expect(Focus.of(container1.currentContext!).hasFocus, isFalse);
      Focus.of(focus2.currentContext!).requestFocus(); // Try to focus focus1
1545
      await tester.pump();
1546 1547
      expect(Focus.of(container1.currentContext!).hasFocus, isFalse);
      Focus.of(container1.currentContext!).requestFocus(); // Try to focus focus2
1548
      await tester.pump();
1549
      expect(Focus.of(container1.currentContext!).hasFocus, isFalse);
1550 1551
      await pumpTest();
      // Try again, now that we've set scope1's canRequestFocus to true again.
1552
      Focus.of(container1.currentContext!).requestFocus();
1553
      await tester.pump();
1554
      expect(Focus.of(container1.currentContext!).hasFocus, isTrue);
1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582
    });

    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(),
1583 1584 1585 1586
                ),
              ),
            ),
          ),
1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613
        );
        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]));
    });
    testWidgets('descendantsAreFocusable works as expected.', (WidgetTester tester) async {
      final GlobalKey key1 = GlobalKey(debugLabel: '1');
      final GlobalKey key2 = GlobalKey(debugLabel: '2');
      final FocusNode focusNode = FocusNode();
1614
      bool? gotFocus;
1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625
      await tester.pumpWidget(
        Focus(
          descendantsAreFocusable: false,
          child: Focus(
            onFocusChange: (bool focused) => gotFocus = focused,
            child: Focus(
              key: key1,
              focusNode: focusNode,
              child: Container(key: key2),
            ),
          ),
1626 1627
        ),
      );
1628 1629

      final Element childWidget = tester.element(find.byKey(key1));
1630
      final FocusNode unfocusableNode = Focus.of(childWidget);
1631
      final Element containerWidget = tester.element(find.byKey(key2));
1632
      final FocusNode containerNode = Focus.of(containerWidget);
1633 1634 1635 1636 1637 1638 1639 1640 1641

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

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

      containerNode.requestFocus();
1642 1643
      await tester.pump();

1644 1645 1646 1647
      expect(gotFocus, isNull);
      expect(containerNode.hasFocus, isFalse);
      expect(unfocusableNode.hasFocus, isFalse);
    });
1648 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 1676 1677 1678 1679 1680 1681

    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>[]));
    });

1682 1683 1684 1685 1686 1687
    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));
    });
1688

1689 1690 1691 1692
    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;
1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705
      // ignore: prefer_function_declarations_over_variables
      final FocusOnKeyCallback handleCallback = (FocusNode node, RawKeyEvent event) {
        keyEventHandled = true;
        return KeyEventResult.handled;
      };
      // ignore: prefer_function_declarations_over_variables
      final FocusOnKeyCallback ignoreCallback = (FocusNode node, RawKeyEvent event) => KeyEventResult.ignored;
      Focus focusWidget = Focus(
        onKey: ignoreCallback, // This one does nothing.
        focusNode: focusNode,
        skipTraversal: true,
        canRequestFocus: true,
        child: Container(key: key1),
1706
      );
1707 1708 1709 1710 1711 1712 1713 1714
      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));
1715 1716 1717 1718 1719 1720

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

1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738
      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);
    });
1739

1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789
    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;
      // ignore: prefer_function_declarations_over_variables
      final FocusOnKeyEventCallback handleEventCallback = (FocusNode node, KeyEvent event) {
        keyEventHandled = true;
        return KeyEventResult.handled;
      };
      // ignore: prefer_function_declarations_over_variables
      final FocusOnKeyEventCallback ignoreEventCallback = (FocusNode node, KeyEvent event) => KeyEventResult.ignored;
      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);
    });
1790

1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811
    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;
      // ignore: prefer_function_declarations_over_variables
      final FocusOnKeyCallback handleCallback = (FocusNode node, RawKeyEvent event) {
        keyEventHandled = true;
        return KeyEventResult.handled;
      };
      // ignore: prefer_function_declarations_over_variables
      final FocusOnKeyEventCallback handleEventCallback = (FocusNode node, KeyEvent event) {
        keyEventHandled = true;
        return KeyEventResult.handled;
      };
      // ignore: prefer_function_declarations_over_variables
      final FocusOnKeyCallback ignoreCallback = (FocusNode node, RawKeyEvent event) => KeyEventResult.ignored;
      // ignore: prefer_function_declarations_over_variables
      final FocusOnKeyEventCallback ignoreEventCallback = (FocusNode node, KeyEvent event) => KeyEventResult.ignored;
      focusNode.onKey = ignoreCallback;
      focusNode.onKeyEvent = ignoreEventCallback;
      focusNode.descendantsAreFocusable = false;
1812
      focusNode.descendantsAreTraversable = false;
1813 1814 1815 1816 1817 1818 1819 1820 1821 1822
      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);
1823
      expect(focusNode.descendantsAreTraversable, isFalse);
1824 1825 1826 1827 1828
      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));
1829
      expect(focusWidget.descendantsAreTraversable, equals(focusNode.descendantsAreTraversable));
1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840
      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;
1841
      focusNode.descendantsAreTraversable = true;
1842 1843 1844
      focusWidget = Focus.withExternalFocusNode(
        focusNode: focusNode,
        child: Container(key: key1),
1845
      );
1846 1847 1848 1849
      await tester.pumpWidget(focusWidget);
      expect(focusNode.onKey, equals(handleCallback));
      expect(focusNode.onKeyEvent, equals(handleEventCallback));
      expect(focusNode.descendantsAreFocusable, isTrue);
1850
      expect(focusNode.descendantsAreTraversable, isTrue);
1851 1852 1853 1854 1855
      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));
1856
      expect(focusWidget.descendantsAreTraversable, equals(focusNode.descendantsAreTraversable));
1857 1858
      expect(focusWidget.skipTraversal, equals(focusNode.skipTraversal));
      expect(focusWidget.canRequestFocus, equals(focusNode.canRequestFocus));
1859 1860 1861 1862

      await tester.sendKeyEvent(LogicalKeyboardKey.enter);
      expect(keyEventHandled, isTrue);
    });
1863 1864 1865 1866 1867 1868 1869 1870

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

1873
  group('ExcludeFocus', () {
1874 1875 1876 1877
    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();
1878
      bool? gotFocus;
1879
      await tester.pumpWidget(
1880 1881 1882
        ExcludeFocus(
          child: Focus(
            onFocusChange: (bool focused) => gotFocus = focused,
1883
            child: Focus(
1884 1885 1886
              key: key1,
              focusNode: focusNode,
              child: Container(key: key2),
1887 1888 1889 1890 1891
            ),
          ),
        ),
      );

1892
      final Element childWidget = tester.element(find.byKey(key1));
1893
      final FocusNode unfocusableNode = Focus.of(childWidget);
1894
      final Element containerWidget = tester.element(find.byKey(key2));
1895
      final FocusNode containerNode = Focus.of(containerWidget);
1896

1897 1898
      unfocusableNode.requestFocus();
      await tester.pump();
1899

1900 1901 1902
      expect(gotFocus, isNull);
      expect(containerNode.hasFocus, isFalse);
      expect(unfocusableNode.hasFocus, isFalse);
1903

1904 1905
      containerNode.requestFocus();
      await tester.pump();
1906

1907 1908 1909 1910
      expect(gotFocus, isNull);
      expect(containerNode.hasFocus, isFalse);
      expect(unfocusableNode.hasFocus, isFalse);
    });
1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977
    // 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);
1978
      expect(parentFocusNode.enclosingScope!.hasPrimaryFocus, isTrue);
1979
    });
1980

1981 1982 1983 1984 1985 1986
    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));
    });
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

    // 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);
    });
2018
  });
2019
}