focus_manager_test.dart 74.4 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
import 'dart:math' as math;

7
import 'package:flutter/foundation.dart';
8
import 'package:flutter/gestures.dart';
9
import 'package:flutter/material.dart';
10
import 'package:flutter/rendering.dart';
11 12 13 14 15 16 17 18
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';

void main() {
  final GlobalKey widgetKey = GlobalKey();
  Future<BuildContext> setupWidget(WidgetTester tester) async {
    await tester.pumpWidget(Container(key: widgetKey));
19
    return widgetKey.currentContext!;
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
  }

  group(FocusNode, () {
    testWidgets('Can add children.', (WidgetTester tester) async {
      final BuildContext context = await setupWidget(tester);
      final FocusNode parent = FocusNode();
      final FocusAttachment parentAttachment = parent.attach(context);
      final FocusNode child1 = FocusNode();
      final FocusAttachment child1Attachment = child1.attach(context);
      final FocusNode child2 = FocusNode();
      final FocusAttachment child2Attachment = child2.attach(context);
      parentAttachment.reparent(parent: tester.binding.focusManager.rootScope);
      child1Attachment.reparent(parent: parent);
      expect(child1.parent, equals(parent));
      expect(parent.children.first, equals(child1));
      expect(parent.children.last, equals(child1));
      child2Attachment.reparent(parent: parent);
      expect(child1.parent, equals(parent));
      expect(child2.parent, equals(parent));
      expect(parent.children.first, equals(child1));
      expect(parent.children.last, equals(child2));
    });
42

43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
    testWidgets('Can remove children.', (WidgetTester tester) async {
      final BuildContext context = await setupWidget(tester);
      final FocusNode parent = FocusNode();
      final FocusAttachment parentAttachment = parent.attach(context);
      final FocusNode child1 = FocusNode();
      final FocusAttachment child1Attachment = child1.attach(context);
      final FocusNode child2 = FocusNode();
      final FocusAttachment child2Attachment = child2.attach(context);
      parentAttachment.reparent(parent: tester.binding.focusManager.rootScope);
      child1Attachment.reparent(parent: parent);
      child2Attachment.reparent(parent: parent);
      expect(child1.parent, equals(parent));
      expect(child2.parent, equals(parent));
      expect(parent.children.first, equals(child1));
      expect(parent.children.last, equals(child2));
      child1Attachment.detach();
      expect(child1.parent, isNull);
      expect(child2.parent, equals(parent));
      expect(parent.children.first, equals(child2));
      expect(parent.children.last, equals(child2));
      child2Attachment.detach();
      expect(child1.parent, isNull);
      expect(child2.parent, isNull);
      expect(parent.children, isEmpty);
    });
68

69 70 71 72 73 74 75 76
    testWidgets('Geometry is transformed properly.', (WidgetTester tester) async {
      final FocusNode focusNode1 = FocusNode(debugLabel: 'Test Node 1');
      final FocusNode focusNode2 = FocusNode(debugLabel: 'Test Node 2');
      await tester.pumpWidget(
        Padding(
          padding: const EdgeInsets.all(8.0),
          child: Column(
            children: <Widget>[
77 78 79 80
              Focus(
                focusNode: focusNode1,
                child: const SizedBox(width: 200, height: 100),
              ),
81 82 83 84 85 86
              Transform.translate(
                offset: const Offset(10, 20),
                child: Transform.scale(
                  scale: 0.33,
                  child: Transform.rotate(
                    angle: math.pi,
87
                    child: Focus(focusNode: focusNode2, child: const SizedBox(width: 200, height: 100)),
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
                  ),
                ),
              ),
            ],
          ),
        ),
      );
      focusNode2.requestFocus();
      await tester.pump();

      expect(focusNode1.rect, equals(const Rect.fromLTRB(300.0, 8.0, 500.0, 108.0)));
      expect(focusNode2.rect, equals(const Rect.fromLTRB(443.0, 194.5, 377.0, 161.5)));
      expect(focusNode1.size, equals(const Size(200.0, 100.0)));
      expect(focusNode2.size, equals(const Size(-66.0, -33.0)));
      expect(focusNode1.offset, equals(const Offset(300.0, 8.0)));
      expect(focusNode2.offset, equals(const Offset(443.0, 194.5)));
    });
105

106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
    testWidgets('descendantsAreFocusable disables focus for descendants.', (WidgetTester tester) async {
      final BuildContext context = await setupWidget(tester);
      final FocusScopeNode scope = FocusScopeNode(debugLabel: 'Scope');
      final FocusAttachment scopeAttachment = scope.attach(context);
      final FocusNode parent1 = FocusNode(debugLabel: 'Parent 1');
      final FocusAttachment parent1Attachment = parent1.attach(context);
      final FocusNode parent2 = FocusNode(debugLabel: 'Parent 2');
      final FocusAttachment parent2Attachment = parent2.attach(context);
      final FocusNode child1 = FocusNode(debugLabel: 'Child 1');
      final FocusAttachment child1Attachment = child1.attach(context);
      final FocusNode child2 = FocusNode(debugLabel: 'Child 2');
      final FocusAttachment child2Attachment = child2.attach(context);
      scopeAttachment.reparent(parent: tester.binding.focusManager.rootScope);
      parent1Attachment.reparent(parent: scope);
      parent2Attachment.reparent(parent: scope);
      child1Attachment.reparent(parent: parent1);
      child2Attachment.reparent(parent: parent2);
      child1.requestFocus();
      await tester.pump();

      expect(tester.binding.focusManager.primaryFocus, equals(child1));
      expect(scope.focusedChild, equals(child1));
      expect(scope.traversalDescendants.contains(child1), isTrue);
      expect(scope.traversalDescendants.contains(child2), isTrue);

      parent2.descendantsAreFocusable = false;
      // Node should still be focusable, even if descendants are not.
      parent2.requestFocus();
      await tester.pump();
      expect(parent2.hasPrimaryFocus, isTrue);

      child2.requestFocus();
      await tester.pump();
      expect(tester.binding.focusManager.primaryFocus, isNot(equals(child2)));
      expect(tester.binding.focusManager.primaryFocus, equals(parent2));
      expect(scope.focusedChild, equals(parent2));
      expect(scope.traversalDescendants.contains(child1), isTrue);
      expect(scope.traversalDescendants.contains(child2), isFalse);

      parent1.descendantsAreFocusable = false;
      await tester.pump();
      expect(tester.binding.focusManager.primaryFocus, isNot(equals(child2)));
      expect(tester.binding.focusManager.primaryFocus, isNot(equals(child1)));
      expect(scope.focusedChild, equals(parent2));
      expect(scope.traversalDescendants.contains(child1), isFalse);
      expect(scope.traversalDescendants.contains(child2), isFalse);
    });
153

154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186
    testWidgets('descendantsAreTraversable disables traversal for descendants.', (WidgetTester tester) async {
      final BuildContext context = await setupWidget(tester);
      final FocusScopeNode scope = FocusScopeNode(debugLabel: 'Scope');
      final FocusAttachment scopeAttachment = scope.attach(context);
      final FocusNode parent1 = FocusNode(debugLabel: 'Parent 1');
      final FocusAttachment parent1Attachment = parent1.attach(context);
      final FocusNode parent2 = FocusNode(debugLabel: 'Parent 2');
      final FocusAttachment parent2Attachment = parent2.attach(context);
      final FocusNode child1 = FocusNode(debugLabel: 'Child 1');
      final FocusAttachment child1Attachment = child1.attach(context);
      final FocusNode child2 = FocusNode(debugLabel: 'Child 2');
      final FocusAttachment child2Attachment = child2.attach(context);

      scopeAttachment.reparent(parent: tester.binding.focusManager.rootScope);
      parent1Attachment.reparent(parent: scope);
      parent2Attachment.reparent(parent: scope);
      child1Attachment.reparent(parent: parent1);
      child2Attachment.reparent(parent: parent2);

      expect(scope.traversalDescendants, equals(<FocusNode>[child1, parent1, child2, parent2]));

      parent2.descendantsAreTraversable = false;
      expect(scope.traversalDescendants, equals(<FocusNode>[child1, parent1, parent2]));

      parent1.descendantsAreTraversable = false;
      expect(scope.traversalDescendants, equals(<FocusNode>[parent1, parent2]));

      parent1.descendantsAreTraversable = true;
      parent2.descendantsAreTraversable = true;
      scope.descendantsAreTraversable = false;
      expect(scope.traversalDescendants, equals(<FocusNode>[]));
    });

187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
    testWidgets("canRequestFocus doesn't affect traversalChildren", (WidgetTester tester) async {
      final BuildContext context = await setupWidget(tester);
      final FocusScopeNode scope = FocusScopeNode(debugLabel: 'Scope');
      final FocusAttachment scopeAttachment = scope.attach(context);
      final FocusNode parent1 = FocusNode(debugLabel: 'Parent 1');
      final FocusAttachment parent1Attachment = parent1.attach(context);
      final FocusNode parent2 = FocusNode(debugLabel: 'Parent 2');
      final FocusAttachment parent2Attachment = parent2.attach(context);
      final FocusNode child1 = FocusNode(debugLabel: 'Child 1');
      final FocusAttachment child1Attachment = child1.attach(context);
      final FocusNode child2 = FocusNode(debugLabel: 'Child 2');
      final FocusAttachment child2Attachment = child2.attach(context);
      scopeAttachment.reparent(parent: tester.binding.focusManager.rootScope);
      parent1Attachment.reparent(parent: scope);
      parent2Attachment.reparent(parent: scope);
      child1Attachment.reparent(parent: parent1);
      child2Attachment.reparent(parent: parent2);
      child1.requestFocus();
      await tester.pump();

      expect(tester.binding.focusManager.primaryFocus, equals(child1));
      expect(scope.focusedChild, equals(child1));
      expect(parent2.traversalChildren.contains(child2), isTrue);
      expect(scope.traversalChildren.contains(parent2), isTrue);

      parent2.canRequestFocus = false;
      await tester.pump();
      expect(parent2.traversalChildren.contains(child2), isTrue);
      expect(scope.traversalChildren.contains(parent2), isFalse);
    });

218 219 220 221 222
    testWidgets('implements debugFillProperties', (WidgetTester tester) async {
      final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder();
      FocusNode(
        debugLabel: 'Label',
      ).debugFillProperties(builder);
223
      final List<String> description = builder.properties.map((DiagnosticsNode n) => n.toString()).toList();
224
      expect(description, <String>[
225
        'context: null',
226
        'descendantsAreFocusable: true',
227
        'descendantsAreTraversable: true',
228 229
        'canRequestFocus: true',
        'hasFocus: false',
230
        'hasPrimaryFocus: false',
231 232
      ]);
    });
233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325

    testWidgets('onKeyEvent and onKey correctly cooperate', (WidgetTester tester) async {
      final FocusNode focusNode = FocusNode(debugLabel: 'Test Node 3');
      List<List<KeyEventResult>> results = <List<KeyEventResult>>[
        <KeyEventResult>[KeyEventResult.ignored, KeyEventResult.ignored],
        <KeyEventResult>[KeyEventResult.ignored, KeyEventResult.ignored],
        <KeyEventResult>[KeyEventResult.ignored, KeyEventResult.ignored],
      ];
      final List<int> logs = <int>[];

      await tester.pumpWidget(
        Focus(
          focusNode: FocusNode(debugLabel: 'Test Node 1'),
          onKeyEvent: (_, KeyEvent event) {
            logs.add(0);
            return results[0][0];
          },
          onKey: (_, RawKeyEvent event) {
            logs.add(1);
            return results[0][1];
          },
          child: Focus(
            focusNode: FocusNode(debugLabel: 'Test Node 2'),
            onKeyEvent: (_, KeyEvent event) {
              logs.add(10);
              return results[1][0];
            },
            onKey: (_, RawKeyEvent event) {
              logs.add(11);
              return results[1][1];
            },
            child: Focus(
              focusNode: focusNode,
              onKeyEvent: (_, KeyEvent event) {
                logs.add(20);
                return results[2][0];
              },
              onKey: (_, RawKeyEvent event) {
                logs.add(21);
                return results[2][1];
              },
              child: const SizedBox(width: 200, height: 100),
            ),
          ),
        ),
      );
      focusNode.requestFocus();
      await tester.pump();

      // All ignored.
      results = <List<KeyEventResult>>[
        <KeyEventResult>[KeyEventResult.ignored, KeyEventResult.ignored],
        <KeyEventResult>[KeyEventResult.ignored, KeyEventResult.ignored],
        <KeyEventResult>[KeyEventResult.ignored, KeyEventResult.ignored],
      ];
      expect(await simulateKeyDownEvent(LogicalKeyboardKey.digit1),
          false);
      expect(logs, <int>[20, 21, 10, 11, 0, 1]);
      logs.clear();

      // The onKeyEvent should be able to stop propagation.
      results = <List<KeyEventResult>>[
        <KeyEventResult>[KeyEventResult.ignored, KeyEventResult.ignored],
        <KeyEventResult>[KeyEventResult.handled, KeyEventResult.ignored],
        <KeyEventResult>[KeyEventResult.ignored, KeyEventResult.ignored],
      ];
      expect(await simulateKeyUpEvent(LogicalKeyboardKey.digit1),
          true);
      expect(logs, <int>[20, 21, 10, 11]);
      logs.clear();

      // The onKey should be able to stop propagation.
      results = <List<KeyEventResult>>[
        <KeyEventResult>[KeyEventResult.ignored, KeyEventResult.ignored],
        <KeyEventResult>[KeyEventResult.ignored, KeyEventResult.handled],
        <KeyEventResult>[KeyEventResult.ignored, KeyEventResult.ignored],
      ];
      expect(await simulateKeyDownEvent(LogicalKeyboardKey.digit1),
          true);
      expect(logs, <int>[20, 21, 10, 11]);
      logs.clear();

      // KeyEventResult.skipRemainingHandlers works.
      results = <List<KeyEventResult>>[
        <KeyEventResult>[KeyEventResult.ignored, KeyEventResult.ignored],
        <KeyEventResult>[KeyEventResult.skipRemainingHandlers, KeyEventResult.ignored],
        <KeyEventResult>[KeyEventResult.ignored, KeyEventResult.ignored],
      ];
      expect(await simulateKeyUpEvent(LogicalKeyboardKey.digit1),
          false);
      expect(logs, <int>[20, 21, 10, 11]);
      logs.clear();
    }, variant: KeySimulatorTransitModeVariant.all());
326
  });
327

328
  group(FocusScopeNode, () {
329

330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353
    testWidgets('Can setFirstFocus on a scope with no manager.', (WidgetTester tester) async {
      final BuildContext context = await setupWidget(tester);
      final FocusScopeNode scope = FocusScopeNode(debugLabel: 'Scope');
      scope.attach(context);
      final FocusScopeNode parent = FocusScopeNode(debugLabel: 'Parent');
      parent.attach(context);
      final FocusScopeNode child1 = FocusScopeNode(debugLabel: 'Child 1');
      final FocusAttachment child1Attachment = child1.attach(context);
      final FocusScopeNode child2 = FocusScopeNode(debugLabel: 'Child 2');
      child2.attach(context);
      scope.setFirstFocus(parent);
      parent.setFirstFocus(child1);
      parent.setFirstFocus(child2);
      child1.requestFocus();
      await tester.pump();
      expect(scope.hasFocus, isFalse);
      expect(child1.hasFocus, isFalse);
      expect(child1.hasPrimaryFocus, isFalse);
      expect(scope.focusedChild, equals(parent));
      expect(parent.focusedChild, equals(child1));
      child1Attachment.detach();
      expect(scope.hasFocus, isFalse);
      expect(scope.focusedChild, equals(parent));
    });
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
    testWidgets('Removing a node removes it from scope.', (WidgetTester tester) async {
      final BuildContext context = await setupWidget(tester);
      final FocusScopeNode scope = FocusScopeNode();
      final FocusAttachment scopeAttachment = scope.attach(context);
      final FocusNode parent = FocusNode();
      final FocusAttachment parentAttachment = parent.attach(context);
      final FocusNode child1 = FocusNode();
      final FocusAttachment child1Attachment = child1.attach(context);
      final FocusNode child2 = FocusNode();
      final FocusAttachment child2Attachment = child2.attach(context);
      scopeAttachment.reparent(parent: tester.binding.focusManager.rootScope);
      parentAttachment.reparent(parent: scope);
      child1Attachment.reparent(parent: parent);
      child2Attachment.reparent(parent: parent);
      child1.requestFocus();
      await tester.pump();
      expect(scope.hasFocus, isTrue);
      expect(child1.hasFocus, isTrue);
      expect(child1.hasPrimaryFocus, isTrue);
      expect(scope.focusedChild, equals(child1));
      child1Attachment.detach();
      expect(scope.hasFocus, isFalse);
      expect(scope.focusedChild, isNull);
    });
379

380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418
    testWidgets('Can add children to scope and focus', (WidgetTester tester) async {
      final BuildContext context = await setupWidget(tester);
      final FocusScopeNode scope = FocusScopeNode();
      final FocusAttachment scopeAttachment = scope.attach(context);
      final FocusNode parent = FocusNode();
      final FocusAttachment parentAttachment = parent.attach(context);
      final FocusNode child1 = FocusNode();
      final FocusAttachment child1Attachment = child1.attach(context);
      final FocusNode child2 = FocusNode();
      final FocusAttachment child2Attachment = child2.attach(context);
      scopeAttachment.reparent(parent: tester.binding.focusManager.rootScope);
      parentAttachment.reparent(parent: scope);
      child1Attachment.reparent(parent: parent);
      child2Attachment.reparent(parent: parent);
      expect(scope.children.first, equals(parent));
      expect(parent.parent, equals(scope));
      expect(child1.parent, equals(parent));
      expect(child2.parent, equals(parent));
      expect(parent.children.first, equals(child1));
      expect(parent.children.last, equals(child2));
      child1.requestFocus();
      await tester.pump();
      expect(scope.focusedChild, equals(child1));
      expect(parent.hasFocus, isTrue);
      expect(parent.hasPrimaryFocus, isFalse);
      expect(child1.hasFocus, isTrue);
      expect(child1.hasPrimaryFocus, isTrue);
      expect(child2.hasFocus, isFalse);
      expect(child2.hasPrimaryFocus, isFalse);
      child2.requestFocus();
      await tester.pump();
      expect(scope.focusedChild, equals(child2));
      expect(parent.hasFocus, isTrue);
      expect(parent.hasPrimaryFocus, isFalse);
      expect(child1.hasFocus, isFalse);
      expect(child1.hasPrimaryFocus, isFalse);
      expect(child2.hasFocus, isTrue);
      expect(child2.hasPrimaryFocus, isTrue);
    });
419

420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438
    testWidgets('Requesting focus before adding to tree results in a request after adding', (WidgetTester tester) async {
      final BuildContext context = await setupWidget(tester);
      final FocusScopeNode scope = FocusScopeNode();
      final FocusAttachment scopeAttachment = scope.attach(context);
      final FocusNode child = FocusNode();
      child.requestFocus();
      expect(child.hasPrimaryFocus, isFalse); // not attached yet.

      scopeAttachment.reparent(parent: tester.binding.focusManager.rootScope);
      await tester.pump();
      expect(scope.focusedChild, isNull);
      expect(child.hasPrimaryFocus, isFalse); // not attached yet.

      final FocusAttachment childAttachment = child.attach(context);
      expect(child.hasPrimaryFocus, isFalse); // not parented yet.
      childAttachment.reparent(parent: scope);
      await tester.pump();
      expect(child.hasPrimaryFocus, isTrue); // now attached and parented, so focus finally happened.
    });
439

440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475
    testWidgets('Autofocus works.', (WidgetTester tester) async {
      final BuildContext context = await setupWidget(tester);
      final FocusScopeNode scope = FocusScopeNode(debugLabel: 'Scope');
      final FocusAttachment scopeAttachment = scope.attach(context);
      final FocusNode parent = FocusNode(debugLabel: 'Parent');
      final FocusAttachment parentAttachment = parent.attach(context);
      final FocusNode child1 = FocusNode(debugLabel: 'Child 1');
      final FocusAttachment child1Attachment = child1.attach(context);
      final FocusNode child2 = FocusNode(debugLabel: 'Child 2');
      final FocusAttachment child2Attachment = child2.attach(context);
      scopeAttachment.reparent(parent: tester.binding.focusManager.rootScope);
      parentAttachment.reparent(parent: scope);
      child1Attachment.reparent(parent: parent);
      child2Attachment.reparent(parent: parent);

      scope.autofocus(child2);
      await tester.pump();

      expect(scope.focusedChild, equals(child2));
      expect(parent.hasFocus, isTrue);
      expect(child1.hasFocus, isFalse);
      expect(child1.hasPrimaryFocus, isFalse);
      expect(child2.hasFocus, isTrue);
      expect(child2.hasPrimaryFocus, isTrue);
      child1.requestFocus();
      scope.autofocus(child2);

      await tester.pump();

      expect(scope.focusedChild, equals(child1));
      expect(parent.hasFocus, isTrue);
      expect(child1.hasFocus, isTrue);
      expect(child1.hasPrimaryFocus, isTrue);
      expect(child2.hasFocus, isFalse);
      expect(child2.hasPrimaryFocus, isFalse);
    });
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
    testWidgets('Adding a focusedChild to a scope sets scope as focusedChild in parent scope', (WidgetTester tester) async {
      final BuildContext context = await setupWidget(tester);
      final FocusScopeNode scope1 = FocusScopeNode();
      final FocusAttachment scope1Attachment = scope1.attach(context);
      final FocusScopeNode scope2 = FocusScopeNode();
      final FocusAttachment scope2Attachment = scope2.attach(context);
      final FocusNode child1 = FocusNode();
      final FocusAttachment child1Attachment = child1.attach(context);
      final FocusNode child2 = FocusNode();
      final FocusAttachment child2Attachment = child2.attach(context);
      scope1Attachment.reparent(parent: tester.binding.focusManager.rootScope);
      scope2Attachment.reparent(parent: scope1);
      child1Attachment.reparent(parent: scope1);
      child2Attachment.reparent(parent: scope2);
      child2.requestFocus();
      await tester.pump();
      expect(scope2.focusedChild, equals(child2));
      expect(scope1.focusedChild, equals(scope2));
      expect(child1.hasFocus, isFalse);
      expect(child1.hasPrimaryFocus, isFalse);
      expect(child2.hasFocus, isTrue);
      expect(child2.hasPrimaryFocus, isTrue);
      child1.requestFocus();
      await tester.pump();
      expect(scope2.focusedChild, equals(child2));
      expect(scope1.focusedChild, equals(child1));
      expect(child1.hasFocus, isTrue);
      expect(child1.hasPrimaryFocus, isTrue);
      expect(child2.hasFocus, isFalse);
      expect(child2.hasPrimaryFocus, isFalse);
    });
508

509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544
    testWidgets('Can move node with focus without losing focus', (WidgetTester tester) async {
      final BuildContext context = await setupWidget(tester);
      final FocusScopeNode scope = FocusScopeNode(debugLabel: 'Scope');
      final FocusAttachment scopeAttachment = scope.attach(context);
      final FocusNode parent1 = FocusNode(debugLabel: 'Parent 1');
      final FocusAttachment parent1Attachment = parent1.attach(context);
      final FocusNode parent2 = FocusNode(debugLabel: 'Parent 2');
      final FocusAttachment parent2Attachment = parent2.attach(context);
      final FocusNode child1 = FocusNode(debugLabel: 'Child 1');
      final FocusAttachment child1Attachment = child1.attach(context);
      final FocusNode child2 = FocusNode(debugLabel: 'Child 2');
      final FocusAttachment child2Attachment = child2.attach(context);
      scopeAttachment.reparent(parent: tester.binding.focusManager.rootScope);
      parent1Attachment.reparent(parent: scope);
      parent2Attachment.reparent(parent: scope);
      child1Attachment.reparent(parent: parent1);
      child2Attachment.reparent(parent: parent1);
      expect(scope.children.first, equals(parent1));
      expect(scope.children.last, equals(parent2));
      expect(parent1.parent, equals(scope));
      expect(parent2.parent, equals(scope));
      expect(child1.parent, equals(parent1));
      expect(child2.parent, equals(parent1));
      expect(parent1.children.first, equals(child1));
      expect(parent1.children.last, equals(child2));
      child1.requestFocus();
      await tester.pump();
      child1Attachment.reparent(parent: parent2);
      await tester.pump();

      expect(scope.focusedChild, equals(child1));
      expect(child1.parent, equals(parent2));
      expect(child2.parent, equals(parent1));
      expect(parent1.children.first, equals(child2));
      expect(parent2.children.first, equals(child1));
    });
545

546 547
    testWidgets('canRequestFocus affects children.', (WidgetTester tester) async {
      final BuildContext context = await setupWidget(tester);
548
      final FocusScopeNode scope = FocusScopeNode(debugLabel: 'Scope');
549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569
      final FocusAttachment scopeAttachment = scope.attach(context);
      final FocusNode parent1 = FocusNode(debugLabel: 'Parent 1');
      final FocusAttachment parent1Attachment = parent1.attach(context);
      final FocusNode parent2 = FocusNode(debugLabel: 'Parent 2');
      final FocusAttachment parent2Attachment = parent2.attach(context);
      final FocusNode child1 = FocusNode(debugLabel: 'Child 1');
      final FocusAttachment child1Attachment = child1.attach(context);
      final FocusNode child2 = FocusNode(debugLabel: 'Child 2');
      final FocusAttachment child2Attachment = child2.attach(context);
      scopeAttachment.reparent(parent: tester.binding.focusManager.rootScope);
      parent1Attachment.reparent(parent: scope);
      parent2Attachment.reparent(parent: scope);
      child1Attachment.reparent(parent: parent1);
      child2Attachment.reparent(parent: parent1);
      child1.requestFocus();
      await tester.pump();

      expect(tester.binding.focusManager.primaryFocus, equals(child1));
      expect(scope.focusedChild, equals(child1));
      expect(scope.traversalDescendants.contains(child1), isTrue);
      expect(scope.traversalDescendants.contains(child2), isTrue);
570 571
      expect(scope.traversalChildren.contains(parent1), isTrue);
      expect(parent1.traversalChildren.contains(child2), isTrue);
572 573 574 575 576 577 578

      scope.canRequestFocus = false;
      await tester.pump();
      child2.requestFocus();
      await tester.pump();
      expect(tester.binding.focusManager.primaryFocus, isNot(equals(child2)));
      expect(tester.binding.focusManager.primaryFocus, isNot(equals(child1)));
579
      expect(scope.focusedChild, equals(child1));
580 581
      expect(scope.traversalDescendants.contains(child1), isFalse);
      expect(scope.traversalDescendants.contains(child2), isFalse);
582 583
      expect(scope.traversalChildren.contains(parent1), isFalse);
      expect(parent1.traversalChildren.contains(child2), isFalse);
584
    });
585

586 587
    testWidgets("skipTraversal doesn't affect children.", (WidgetTester tester) async {
      final BuildContext context = await setupWidget(tester);
588
      final FocusScopeNode scope = FocusScopeNode(debugLabel: 'Scope');
589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619
      final FocusAttachment scopeAttachment = scope.attach(context);
      final FocusNode parent1 = FocusNode(debugLabel: 'Parent 1');
      final FocusAttachment parent1Attachment = parent1.attach(context);
      final FocusNode parent2 = FocusNode(debugLabel: 'Parent 2');
      final FocusAttachment parent2Attachment = parent2.attach(context);
      final FocusNode child1 = FocusNode(debugLabel: 'Child 1');
      final FocusAttachment child1Attachment = child1.attach(context);
      final FocusNode child2 = FocusNode(debugLabel: 'Child 2');
      final FocusAttachment child2Attachment = child2.attach(context);
      scopeAttachment.reparent(parent: tester.binding.focusManager.rootScope);
      parent1Attachment.reparent(parent: scope);
      parent2Attachment.reparent(parent: scope);
      child1Attachment.reparent(parent: parent1);
      child2Attachment.reparent(parent: parent1);
      child1.requestFocus();
      await tester.pump();

      expect(tester.binding.focusManager.primaryFocus, equals(child1));
      expect(scope.focusedChild, equals(child1));
      expect(tester.binding.focusManager.rootScope.traversalDescendants.contains(scope), isTrue);
      expect(scope.traversalDescendants.contains(child1), isTrue);
      expect(scope.traversalDescendants.contains(child2), isTrue);

      scope.skipTraversal = true;
      await tester.pump();
      expect(tester.binding.focusManager.primaryFocus, equals(child1));
      expect(scope.focusedChild, equals(child1));
      expect(tester.binding.focusManager.rootScope.traversalDescendants.contains(scope), isFalse);
      expect(scope.traversalDescendants.contains(child1), isTrue);
      expect(scope.traversalDescendants.contains(child2), isTrue);
    });
620

621 622
    testWidgets('Can move node between scopes and lose scope focus', (WidgetTester tester) async {
      final BuildContext context = await setupWidget(tester);
623
      final FocusScopeNode scope1 = FocusScopeNode(debugLabel: 'scope1')..attach(context);
624
      final FocusAttachment scope1Attachment = scope1.attach(context);
625
      final FocusScopeNode scope2 = FocusScopeNode(debugLabel: 'scope2');
626
      final FocusAttachment scope2Attachment = scope2.attach(context);
627
      final FocusNode parent1 = FocusNode(debugLabel: 'parent1');
628
      final FocusAttachment parent1Attachment = parent1.attach(context);
629
      final FocusNode parent2 = FocusNode(debugLabel: 'parent2');
630
      final FocusAttachment parent2Attachment = parent2.attach(context);
631
      final FocusNode child1 = FocusNode(debugLabel: 'child1');
632
      final FocusAttachment child1Attachment = child1.attach(context);
633
      final FocusNode child2 = FocusNode(debugLabel: 'child2');
634
      final FocusAttachment child2Attachment = child2.attach(context);
635
      final FocusNode child3 = FocusNode(debugLabel: 'child3');
636
      final FocusAttachment child3Attachment = child3.attach(context);
637
      final FocusNode child4 = FocusNode(debugLabel: 'child4');
638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657
      final FocusAttachment child4Attachment = child4.attach(context);
      scope1Attachment.reparent(parent: tester.binding.focusManager.rootScope);
      scope2Attachment.reparent(parent: tester.binding.focusManager.rootScope);
      parent1Attachment.reparent(parent: scope1);
      parent2Attachment.reparent(parent: scope2);
      child1Attachment.reparent(parent: parent1);
      child2Attachment.reparent(parent: parent1);
      child3Attachment.reparent(parent: parent2);
      child4Attachment.reparent(parent: parent2);

      child1.requestFocus();
      await tester.pump();
      expect(scope1.focusedChild, equals(child1));
      expect(parent2.children.contains(child1), isFalse);

      child1Attachment.reparent(parent: parent2);
      await tester.pump();
      expect(scope1.focusedChild, isNull);
      expect(parent2.children.contains(child1), isTrue);
    });
658

659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693
    testWidgets('ancestors and descendants are computed and recomputed properly', (WidgetTester tester) async {
      final BuildContext context = await setupWidget(tester);
      final FocusScopeNode scope1 = FocusScopeNode(debugLabel: 'scope1');
      final FocusAttachment scope1Attachment = scope1.attach(context);
      final FocusScopeNode scope2 = FocusScopeNode(debugLabel: 'scope2');
      final FocusAttachment scope2Attachment = scope2.attach(context);
      final FocusNode parent1 = FocusNode(debugLabel: 'parent1');
      final FocusAttachment parent1Attachment = parent1.attach(context);
      final FocusNode parent2 = FocusNode(debugLabel: 'parent2');
      final FocusAttachment parent2Attachment = parent2.attach(context);
      final FocusNode child1 = FocusNode(debugLabel: 'child1');
      final FocusAttachment child1Attachment = child1.attach(context);
      final FocusNode child2 = FocusNode(debugLabel: 'child2');
      final FocusAttachment child2Attachment = child2.attach(context);
      final FocusNode child3 = FocusNode(debugLabel: 'child3');
      final FocusAttachment child3Attachment = child3.attach(context);
      final FocusNode child4 = FocusNode(debugLabel: 'child4');
      final FocusAttachment child4Attachment = child4.attach(context);
      scope1Attachment.reparent(parent: tester.binding.focusManager.rootScope);
      scope2Attachment.reparent(parent: tester.binding.focusManager.rootScope);
      parent1Attachment.reparent(parent: scope1);
      parent2Attachment.reparent(parent: scope2);
      child1Attachment.reparent(parent: parent1);
      child2Attachment.reparent(parent: parent1);
      child3Attachment.reparent(parent: parent2);
      child4Attachment.reparent(parent: parent2);
      child4.requestFocus();
      await tester.pump();
      expect(child4.ancestors, equals(<FocusNode>[parent2, scope2, tester.binding.focusManager.rootScope]));
      expect(tester.binding.focusManager.rootScope.descendants, equals(<FocusNode>[child1, child2, parent1, scope1, child3, child4, parent2, scope2]));
      scope2Attachment.reparent(parent: child2);
      await tester.pump();
      expect(child4.ancestors, equals(<FocusNode>[parent2, scope2, child2, parent1, scope1, tester.binding.focusManager.rootScope]));
      expect(tester.binding.focusManager.rootScope.descendants, equals(<FocusNode>[child1, child3, child4, parent2, scope2, child2, parent1, scope1]));
    });
694

695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751
    testWidgets('Can move focus between scopes and keep focus', (WidgetTester tester) async {
      final BuildContext context = await setupWidget(tester);
      final FocusScopeNode scope1 = FocusScopeNode();
      final FocusAttachment scope1Attachment = scope1.attach(context);
      final FocusScopeNode scope2 = FocusScopeNode();
      final FocusAttachment scope2Attachment = scope2.attach(context);
      final FocusNode parent1 = FocusNode();
      final FocusAttachment parent1Attachment = parent1.attach(context);
      final FocusNode parent2 = FocusNode();
      final FocusAttachment parent2Attachment = parent2.attach(context);
      final FocusNode child1 = FocusNode();
      final FocusAttachment child1Attachment = child1.attach(context);
      final FocusNode child2 = FocusNode();
      final FocusAttachment child2Attachment = child2.attach(context);
      final FocusNode child3 = FocusNode();
      final FocusAttachment child3Attachment = child3.attach(context);
      final FocusNode child4 = FocusNode();
      final FocusAttachment child4Attachment = child4.attach(context);
      scope1Attachment.reparent(parent: tester.binding.focusManager.rootScope);
      scope2Attachment.reparent(parent: tester.binding.focusManager.rootScope);
      parent1Attachment.reparent(parent: scope1);
      parent2Attachment.reparent(parent: scope2);
      child1Attachment.reparent(parent: parent1);
      child2Attachment.reparent(parent: parent1);
      child3Attachment.reparent(parent: parent2);
      child4Attachment.reparent(parent: parent2);
      child4.requestFocus();
      await tester.pump();
      child1.requestFocus();
      await tester.pump();
      expect(child4.hasFocus, isFalse);
      expect(child4.hasPrimaryFocus, isFalse);
      expect(child1.hasFocus, isTrue);
      expect(child1.hasPrimaryFocus, isTrue);
      expect(scope1.hasFocus, isTrue);
      expect(scope1.hasPrimaryFocus, isFalse);
      expect(scope2.hasFocus, isFalse);
      expect(scope2.hasPrimaryFocus, isFalse);
      expect(parent1.hasFocus, isTrue);
      expect(parent2.hasFocus, isFalse);
      expect(scope1.focusedChild, equals(child1));
      expect(scope2.focusedChild, equals(child4));
      scope2.requestFocus();
      await tester.pump();
      expect(child4.hasFocus, isTrue);
      expect(child4.hasPrimaryFocus, isTrue);
      expect(child1.hasFocus, isFalse);
      expect(child1.hasPrimaryFocus, isFalse);
      expect(scope1.hasFocus, isFalse);
      expect(scope1.hasPrimaryFocus, isFalse);
      expect(scope2.hasFocus, isTrue);
      expect(scope2.hasPrimaryFocus, isFalse);
      expect(parent1.hasFocus, isFalse);
      expect(parent2.hasFocus, isTrue);
      expect(scope1.focusedChild, equals(child1));
      expect(scope2.focusedChild, equals(child4));
    });
752

753
    testWidgets('Unfocus with disposition previouslyFocusedChild works properly', (WidgetTester tester) async {
754
      final BuildContext context = await setupWidget(tester);
755
      final FocusScopeNode scope1 = FocusScopeNode(debugLabel: 'scope1')..attach(context);
756
      final FocusAttachment scope1Attachment = scope1.attach(context);
757
      final FocusScopeNode scope2 = FocusScopeNode(debugLabel: 'scope2');
758
      final FocusAttachment scope2Attachment = scope2.attach(context);
759
      final FocusNode parent1 = FocusNode(debugLabel: 'parent1');
760
      final FocusAttachment parent1Attachment = parent1.attach(context);
761
      final FocusNode parent2 = FocusNode(debugLabel: 'parent2');
762
      final FocusAttachment parent2Attachment = parent2.attach(context);
763
      final FocusNode child1 = FocusNode(debugLabel: 'child1');
764
      final FocusAttachment child1Attachment = child1.attach(context);
765
      final FocusNode child2 = FocusNode(debugLabel: 'child2');
766
      final FocusAttachment child2Attachment = child2.attach(context);
767
      final FocusNode child3 = FocusNode(debugLabel: 'child3');
768
      final FocusAttachment child3Attachment = child3.attach(context);
769
      final FocusNode child4 = FocusNode(debugLabel: 'child4');
770 771 772 773 774 775 776 777 778 779
      final FocusAttachment child4Attachment = child4.attach(context);
      scope1Attachment.reparent(parent: tester.binding.focusManager.rootScope);
      scope2Attachment.reparent(parent: tester.binding.focusManager.rootScope);
      parent1Attachment.reparent(parent: scope1);
      parent2Attachment.reparent(parent: scope2);
      child1Attachment.reparent(parent: parent1);
      child2Attachment.reparent(parent: parent1);
      child3Attachment.reparent(parent: parent2);
      child4Attachment.reparent(parent: parent2);

780 781 782 783 784 785 786
      // Build up a history.
      child4.requestFocus();
      await tester.pump();
      child2.requestFocus();
      await tester.pump();
      child3.requestFocus();
      await tester.pump();
787 788 789
      child1.requestFocus();
      await tester.pump();
      expect(scope1.focusedChild, equals(child1));
790
      expect(scope2.focusedChild, equals(child3));
791

792
      child1.unfocus(disposition: UnfocusDisposition.previouslyFocusedChild);
793
      await tester.pump();
794 795 796 797
      expect(scope1.focusedChild, equals(child2));
      expect(scope2.focusedChild, equals(child3));
      expect(scope1.hasFocus, isTrue);
      expect(scope2.hasFocus, isFalse);
798
      expect(child1.hasPrimaryFocus, isFalse);
799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827
      expect(child2.hasPrimaryFocus, isTrue);

      // Can re-focus child.
      child1.requestFocus();
      await tester.pump();
      expect(scope1.focusedChild, equals(child1));
      expect(scope2.focusedChild, equals(child3));
      expect(scope1.hasFocus, isTrue);
      expect(scope2.hasFocus, isFalse);
      expect(child1.hasPrimaryFocus, isTrue);
      expect(child3.hasPrimaryFocus, isFalse);

      // The same thing happens when unfocusing a second time.
      child1.unfocus(disposition: UnfocusDisposition.previouslyFocusedChild);
      await tester.pump();
      expect(scope1.focusedChild, equals(child2));
      expect(scope2.focusedChild, equals(child3));
      expect(scope1.hasFocus, isTrue);
      expect(scope2.hasFocus, isFalse);
      expect(child1.hasPrimaryFocus, isFalse);
      expect(child2.hasPrimaryFocus, isTrue);

      // When the scope gets unfocused, then the sibling scope gets focus.
      child1.requestFocus();
      await tester.pump();
      scope1.unfocus(disposition: UnfocusDisposition.previouslyFocusedChild);
      await tester.pump();
      expect(scope1.focusedChild, equals(child1));
      expect(scope2.focusedChild, equals(child3));
828
      expect(scope1.hasFocus, isFalse);
829 830 831 832
      expect(scope2.hasFocus, isTrue);
      expect(child1.hasPrimaryFocus, isFalse);
      expect(child3.hasPrimaryFocus, isTrue);
    });
833

834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859
    testWidgets('Unfocus with disposition scope works properly', (WidgetTester tester) async {
      final BuildContext context = await setupWidget(tester);
      final FocusScopeNode scope1 = FocusScopeNode(debugLabel: 'scope1')..attach(context);
      final FocusAttachment scope1Attachment = scope1.attach(context);
      final FocusScopeNode scope2 = FocusScopeNode(debugLabel: 'scope2');
      final FocusAttachment scope2Attachment = scope2.attach(context);
      final FocusNode parent1 = FocusNode(debugLabel: 'parent1');
      final FocusAttachment parent1Attachment = parent1.attach(context);
      final FocusNode parent2 = FocusNode(debugLabel: 'parent2');
      final FocusAttachment parent2Attachment = parent2.attach(context);
      final FocusNode child1 = FocusNode(debugLabel: 'child1');
      final FocusAttachment child1Attachment = child1.attach(context);
      final FocusNode child2 = FocusNode(debugLabel: 'child2');
      final FocusAttachment child2Attachment = child2.attach(context);
      final FocusNode child3 = FocusNode(debugLabel: 'child3');
      final FocusAttachment child3Attachment = child3.attach(context);
      final FocusNode child4 = FocusNode(debugLabel: 'child4');
      final FocusAttachment child4Attachment = child4.attach(context);
      scope1Attachment.reparent(parent: tester.binding.focusManager.rootScope);
      scope2Attachment.reparent(parent: tester.binding.focusManager.rootScope);
      parent1Attachment.reparent(parent: scope1);
      parent2Attachment.reparent(parent: scope2);
      child1Attachment.reparent(parent: parent1);
      child2Attachment.reparent(parent: parent1);
      child3Attachment.reparent(parent: parent2);
      child4Attachment.reparent(parent: parent2);
860

861 862 863 864 865 866 867
      // Build up a history.
      child4.requestFocus();
      await tester.pump();
      child2.requestFocus();
      await tester.pump();
      child3.requestFocus();
      await tester.pump();
868 869 870
      child1.requestFocus();
      await tester.pump();
      expect(scope1.focusedChild, equals(child1));
871 872
      expect(scope2.focusedChild, equals(child3));

873
      child1.unfocus();
874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892
      await tester.pump();
      // Focused child doesn't change.
      expect(scope1.focusedChild, isNull);
      expect(scope2.focusedChild, equals(child3));
      // Focus does change.
      expect(scope1.hasPrimaryFocus, isTrue);
      expect(scope2.hasFocus, isFalse);
      expect(child1.hasPrimaryFocus, isFalse);
      expect(child2.hasPrimaryFocus, isFalse);

      // Can re-focus child.
      child1.requestFocus();
      await tester.pump();
      expect(scope1.focusedChild, equals(child1));
      expect(scope2.focusedChild, equals(child3));
      expect(scope1.hasFocus, isTrue);
      expect(scope2.hasFocus, isFalse);
      expect(child1.hasPrimaryFocus, isTrue);
      expect(child3.hasPrimaryFocus, isFalse);
893

894
      // The same thing happens when unfocusing a second time.
895
      child1.unfocus();
896 897
      await tester.pump();
      expect(scope1.focusedChild, isNull);
898 899 900
      expect(scope2.focusedChild, equals(child3));
      expect(scope1.hasPrimaryFocus, isTrue);
      expect(scope2.hasFocus, isFalse);
901
      expect(child1.hasPrimaryFocus, isFalse);
902 903 904 905 906 907
      expect(child2.hasPrimaryFocus, isFalse);

      // When the scope gets unfocused, then its parent scope (the root scope)
      // gets focus, but it doesn't mess with the focused children.
      child1.requestFocus();
      await tester.pump();
908
      scope1.unfocus();
909 910 911
      await tester.pump();
      expect(scope1.focusedChild, equals(child1));
      expect(scope2.focusedChild, equals(child3));
912
      expect(scope1.hasFocus, isFalse);
913 914 915 916 917
      expect(scope2.hasFocus, isFalse);
      expect(child1.hasPrimaryFocus, isFalse);
      expect(child3.hasPrimaryFocus, isFalse);
      expect(FocusManager.instance.rootScope.hasPrimaryFocus, isTrue);
    });
918

919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963
    testWidgets('Unfocus works properly when some nodes are unfocusable', (WidgetTester tester) async {
      final BuildContext context = await setupWidget(tester);
      final FocusScopeNode scope1 = FocusScopeNode(debugLabel: 'scope1')..attach(context);
      final FocusAttachment scope1Attachment = scope1.attach(context);
      final FocusScopeNode scope2 = FocusScopeNode(debugLabel: 'scope2');
      final FocusAttachment scope2Attachment = scope2.attach(context);
      final FocusNode parent1 = FocusNode(debugLabel: 'parent1');
      final FocusAttachment parent1Attachment = parent1.attach(context);
      final FocusNode parent2 = FocusNode(debugLabel: 'parent2');
      final FocusAttachment parent2Attachment = parent2.attach(context);
      final FocusNode child1 = FocusNode(debugLabel: 'child1');
      final FocusAttachment child1Attachment = child1.attach(context);
      final FocusNode child2 = FocusNode(debugLabel: 'child2');
      final FocusAttachment child2Attachment = child2.attach(context);
      final FocusNode child3 = FocusNode(debugLabel: 'child3');
      final FocusAttachment child3Attachment = child3.attach(context);
      final FocusNode child4 = FocusNode(debugLabel: 'child4');
      final FocusAttachment child4Attachment = child4.attach(context);
      scope1Attachment.reparent(parent: tester.binding.focusManager.rootScope);
      scope2Attachment.reparent(parent: tester.binding.focusManager.rootScope);
      parent1Attachment.reparent(parent: scope1);
      parent2Attachment.reparent(parent: scope2);
      child1Attachment.reparent(parent: parent1);
      child2Attachment.reparent(parent: parent1);
      child3Attachment.reparent(parent: parent2);
      child4Attachment.reparent(parent: parent2);

      // Build up a history.
      child4.requestFocus();
      await tester.pump();
      child2.requestFocus();
      await tester.pump();
      child3.requestFocus();
      await tester.pump();
      child1.requestFocus();
      await tester.pump();
      expect(child1.hasPrimaryFocus, isTrue);

      scope1.canRequestFocus = false;
      await tester.pump();

      expect(scope1.focusedChild, equals(child1));
      expect(scope2.focusedChild, equals(child3));
      expect(child3.hasPrimaryFocus, isTrue);

964
      child1.unfocus();
965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983
      await tester.pump();
      expect(child3.hasPrimaryFocus, isTrue);
      expect(scope1.focusedChild, equals(child1));
      expect(scope2.focusedChild, equals(child3));
      expect(scope1.hasPrimaryFocus, isFalse);
      expect(scope2.hasFocus, isTrue);
      expect(child1.hasPrimaryFocus, isFalse);
      expect(child2.hasPrimaryFocus, isFalse);

      child1.unfocus(disposition: UnfocusDisposition.previouslyFocusedChild);
      await tester.pump();
      expect(child3.hasPrimaryFocus, isTrue);
      expect(scope1.focusedChild, equals(child1));
      expect(scope2.focusedChild, equals(child3));
      expect(scope1.hasPrimaryFocus, isFalse);
      expect(scope2.hasFocus, isTrue);
      expect(child1.hasPrimaryFocus, isFalse);
      expect(child2.hasPrimaryFocus, isFalse);
    });
984

985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 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 1031 1032 1033 1034 1035 1036
    testWidgets('Requesting focus on a scope works properly when some focusedChild nodes are unfocusable', (WidgetTester tester) async {
      final BuildContext context = await setupWidget(tester);
      final FocusScopeNode scope1 = FocusScopeNode(debugLabel: 'scope1')..attach(context);
      final FocusAttachment scope1Attachment = scope1.attach(context);
      final FocusScopeNode scope2 = FocusScopeNode(debugLabel: 'scope2');
      final FocusAttachment scope2Attachment = scope2.attach(context);
      final FocusNode parent1 = FocusNode(debugLabel: 'parent1');
      final FocusAttachment parent1Attachment = parent1.attach(context);
      final FocusNode parent2 = FocusNode(debugLabel: 'parent2');
      final FocusAttachment parent2Attachment = parent2.attach(context);
      final FocusNode child1 = FocusNode(debugLabel: 'child1');
      final FocusAttachment child1Attachment = child1.attach(context);
      final FocusNode child2 = FocusNode(debugLabel: 'child2');
      final FocusAttachment child2Attachment = child2.attach(context);
      final FocusNode child3 = FocusNode(debugLabel: 'child3');
      final FocusAttachment child3Attachment = child3.attach(context);
      final FocusNode child4 = FocusNode(debugLabel: 'child4');
      final FocusAttachment child4Attachment = child4.attach(context);
      scope1Attachment.reparent(parent: tester.binding.focusManager.rootScope);
      scope2Attachment.reparent(parent: tester.binding.focusManager.rootScope);
      parent1Attachment.reparent(parent: scope1);
      parent2Attachment.reparent(parent: scope2);
      child1Attachment.reparent(parent: parent1);
      child2Attachment.reparent(parent: parent1);
      child3Attachment.reparent(parent: parent2);
      child4Attachment.reparent(parent: parent2);

      // Build up a history.
      child4.requestFocus();
      await tester.pump();
      child2.requestFocus();
      await tester.pump();
      child3.requestFocus();
      await tester.pump();
      child1.requestFocus();
      await tester.pump();
      expect(child1.hasPrimaryFocus, isTrue);

      child1.canRequestFocus = false;
      child3.canRequestFocus = false;
      await tester.pump();
      scope1.requestFocus();
      await tester.pump();

      expect(scope1.focusedChild, equals(child2));
      expect(child2.hasPrimaryFocus, isTrue);

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

      expect(scope2.focusedChild, equals(child4));
      expect(child4.hasPrimaryFocus, isTrue);
1037
    });
1038

1039 1040 1041
    testWidgets('Key handling bubbles up and terminates when handled.', (WidgetTester tester) async {
      final Set<FocusNode> receivedAnEvent = <FocusNode>{};
      final Set<FocusNode> shouldHandle = <FocusNode>{};
1042
      KeyEventResult handleEvent(FocusNode node, RawKeyEvent event) {
1043 1044
        if (shouldHandle.contains(node)) {
          receivedAnEvent.add(node);
1045
          return KeyEventResult.handled;
1046
        }
1047
        return KeyEventResult.ignored;
1048 1049
      }

1050
      Future<void> sendEvent() async {
1051
        receivedAnEvent.clear();
1052
        await tester.sendKeyEvent(LogicalKeyboardKey.metaLeft, platform: 'fuchsia');
1053 1054 1055 1056 1057 1058 1059
      }

      final BuildContext context = await setupWidget(tester);
      final FocusScopeNode scope1 = FocusScopeNode(debugLabel: 'Scope 1');
      final FocusAttachment scope1Attachment = scope1.attach(context, onKey: handleEvent);
      final FocusScopeNode scope2 = FocusScopeNode(debugLabel: 'Scope 2');
      final FocusAttachment scope2Attachment = scope2.attach(context, onKey: handleEvent);
1060 1061 1062 1063
      final FocusNode parent1 = FocusNode(debugLabel: 'Parent 1', onKey: handleEvent);
      final FocusAttachment parent1Attachment = parent1.attach(context);
      final FocusNode parent2 = FocusNode(debugLabel: 'Parent 2', onKey: handleEvent);
      final FocusAttachment parent2Attachment = parent2.attach(context);
1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082
      final FocusNode child1 = FocusNode(debugLabel: 'Child 1');
      final FocusAttachment child1Attachment = child1.attach(context, onKey: handleEvent);
      final FocusNode child2 = FocusNode(debugLabel: 'Child 2');
      final FocusAttachment child2Attachment = child2.attach(context, onKey: handleEvent);
      final FocusNode child3 = FocusNode(debugLabel: 'Child 3');
      final FocusAttachment child3Attachment = child3.attach(context, onKey: handleEvent);
      final FocusNode child4 = FocusNode(debugLabel: 'Child 4');
      final FocusAttachment child4Attachment = child4.attach(context, onKey: handleEvent);
      scope1Attachment.reparent(parent: tester.binding.focusManager.rootScope);
      scope2Attachment.reparent(parent: tester.binding.focusManager.rootScope);
      parent1Attachment.reparent(parent: scope1);
      parent2Attachment.reparent(parent: scope2);
      child1Attachment.reparent(parent: parent1);
      child2Attachment.reparent(parent: parent1);
      child3Attachment.reparent(parent: parent2);
      child4Attachment.reparent(parent: parent2);
      child4.requestFocus();
      await tester.pump();
      shouldHandle.addAll(<FocusNode>{scope2, parent2, child2, child4});
1083
      await sendEvent();
1084 1085
      expect(receivedAnEvent, equals(<FocusNode>{child4}));
      shouldHandle.remove(child4);
1086
      await sendEvent();
1087 1088
      expect(receivedAnEvent, equals(<FocusNode>{parent2}));
      shouldHandle.remove(parent2);
1089
      await sendEvent();
1090 1091
      expect(receivedAnEvent, equals(<FocusNode>{scope2}));
      shouldHandle.clear();
1092
      await sendEvent();
1093 1094 1095 1096
      expect(receivedAnEvent, isEmpty);
      child1.requestFocus();
      await tester.pump();
      shouldHandle.addAll(<FocusNode>{scope2, parent2, child2, child4});
1097
      await sendEvent();
1098 1099 1100
      // Since none of the focused nodes handle this event, nothing should
      // receive it.
      expect(receivedAnEvent, isEmpty);
1101
    }, variant: KeySimulatorTransitModeVariant.all());
1102

1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117
    testWidgets('Initial highlight mode guesses correctly.', (WidgetTester tester) async {
      FocusManager.instance.highlightStrategy = FocusHighlightStrategy.automatic;
      switch (defaultTargetPlatform) {
        case TargetPlatform.fuchsia:
        case TargetPlatform.android:
        case TargetPlatform.iOS:
          expect(FocusManager.instance.highlightMode, equals(FocusHighlightMode.touch));
          break;
        case TargetPlatform.linux:
        case TargetPlatform.macOS:
        case TargetPlatform.windows:
          expect(FocusManager.instance.highlightMode, equals(FocusHighlightMode.traditional));
          break;
      }
    }, variant: TargetPlatformVariant.all());
1118

1119 1120
    testWidgets('Mouse events change initial focus highlight mode on mobile.', (WidgetTester tester) async {
      expect(FocusManager.instance.highlightMode, equals(FocusHighlightMode.touch));
1121
      RendererBinding.instance.initMouseTracker(); // Clear out the mouse state.
1122 1123 1124 1125
      final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse, pointer: 0);
      await gesture.moveTo(Offset.zero);
      expect(FocusManager.instance.highlightMode, equals(FocusHighlightMode.traditional));
    }, variant: TargetPlatformVariant.mobile());
1126

1127 1128
    testWidgets('Mouse events change initial focus highlight mode on desktop.', (WidgetTester tester) async {
      expect(FocusManager.instance.highlightMode, equals(FocusHighlightMode.traditional));
1129
      RendererBinding.instance.initMouseTracker(); // Clear out the mouse state.
1130 1131 1132 1133
      final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse, pointer: 0);
      await gesture.moveTo(Offset.zero);
      expect(FocusManager.instance.highlightMode, equals(FocusHighlightMode.traditional));
    }, variant: TargetPlatformVariant.desktop());
1134

1135 1136 1137 1138
    testWidgets('Keyboard events change initial focus highlight mode.', (WidgetTester tester) async {
      await tester.sendKeyEvent(LogicalKeyboardKey.enter);
      expect(FocusManager.instance.highlightMode, equals(FocusHighlightMode.traditional));
    }, variant: TargetPlatformVariant.all());
1139

1140 1141 1142
    testWidgets('Events change focus highlight mode.', (WidgetTester tester) async {
      await setupWidget(tester);
      int callCount = 0;
1143
      FocusHighlightMode? lastMode;
1144 1145 1146 1147
      void handleModeChange(FocusHighlightMode mode) {
        lastMode = mode;
        callCount++;
      }
1148 1149
      FocusManager.instance.addHighlightModeListener(handleModeChange);
      addTearDown(() => FocusManager.instance.removeHighlightModeListener(handleModeChange));
1150 1151
      expect(callCount, equals(0));
      expect(lastMode, isNull);
1152 1153
      FocusManager.instance.highlightStrategy = FocusHighlightStrategy.automatic;
      expect(FocusManager.instance.highlightMode, equals(FocusHighlightMode.touch));
1154
      await tester.sendKeyEvent(LogicalKeyboardKey.metaLeft, platform: 'fuchsia');
1155 1156
      expect(callCount, equals(1));
      expect(lastMode, FocusHighlightMode.traditional);
1157
      expect(FocusManager.instance.highlightMode, equals(FocusHighlightMode.traditional));
1158
      await tester.tap(find.byType(Container), warnIfMissed: false);
1159 1160
      expect(callCount, equals(2));
      expect(lastMode, FocusHighlightMode.touch);
1161
      expect(FocusManager.instance.highlightMode, equals(FocusHighlightMode.touch));
1162 1163 1164 1165
      final TestGesture gesture = await tester.startGesture(Offset.zero, kind: PointerDeviceKind.mouse);
      await gesture.up();
      expect(callCount, equals(3));
      expect(lastMode, FocusHighlightMode.traditional);
1166
      expect(FocusManager.instance.highlightMode, equals(FocusHighlightMode.traditional));
1167
      await tester.tap(find.byType(Container), warnIfMissed: false);
1168 1169
      expect(callCount, equals(4));
      expect(lastMode, FocusHighlightMode.touch);
1170 1171
      expect(FocusManager.instance.highlightMode, equals(FocusHighlightMode.touch));
      FocusManager.instance.highlightStrategy = FocusHighlightStrategy.alwaysTraditional;
1172 1173
      expect(callCount, equals(5));
      expect(lastMode, FocusHighlightMode.traditional);
1174 1175
      expect(FocusManager.instance.highlightMode, equals(FocusHighlightMode.traditional));
      FocusManager.instance.highlightStrategy = FocusHighlightStrategy.alwaysTouch;
1176 1177
      expect(callCount, equals(6));
      expect(lastMode, FocusHighlightMode.touch);
1178
      expect(FocusManager.instance.highlightMode, equals(FocusHighlightMode.touch));
1179
    });
1180

1181 1182 1183 1184 1185
    testWidgets('implements debugFillProperties', (WidgetTester tester) async {
      final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder();
      FocusScopeNode(
        debugLabel: 'Scope Label',
      ).debugFillProperties(builder);
1186
      final List<String> description = builder.properties.map((DiagnosticsNode n) => n.toString()).toList();
1187
      expect(description, <String>[
1188
        'context: null',
1189
        'descendantsAreFocusable: true',
1190
        'descendantsAreTraversable: true',
1191 1192
        'canRequestFocus: true',
        'hasFocus: false',
1193
        'hasPrimaryFocus: false',
1194 1195
      ]);
    });
1196

1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229
    testWidgets('debugDescribeFocusTree produces correct output', (WidgetTester tester) async {
      final BuildContext context = await setupWidget(tester);
      final FocusScopeNode scope1 = FocusScopeNode(debugLabel: 'Scope 1');
      final FocusAttachment scope1Attachment = scope1.attach(context);
      final FocusScopeNode scope2 = FocusScopeNode(); // No label, Just to test that it works.
      final FocusAttachment scope2Attachment = scope2.attach(context);
      final FocusNode parent1 = FocusNode(debugLabel: 'Parent 1');
      final FocusAttachment parent1Attachment = parent1.attach(context);
      final FocusNode parent2 = FocusNode(debugLabel: 'Parent 2');
      final FocusAttachment parent2Attachment = parent2.attach(context);
      final FocusNode child1 = FocusNode(debugLabel: 'Child 1');
      final FocusAttachment child1Attachment = child1.attach(context);
      final FocusNode child2 = FocusNode(); // No label, Just to test that it works.
      final FocusAttachment child2Attachment = child2.attach(context);
      final FocusNode child3 = FocusNode(debugLabel: 'Child 3');
      final FocusAttachment child3Attachment = child3.attach(context);
      final FocusNode child4 = FocusNode(debugLabel: 'Child 4');
      final FocusAttachment child4Attachment = child4.attach(context);
      scope1Attachment.reparent(parent: tester.binding.focusManager.rootScope);
      scope2Attachment.reparent(parent: tester.binding.focusManager.rootScope);
      parent1Attachment.reparent(parent: scope1);
      parent2Attachment.reparent(parent: scope2);
      child1Attachment.reparent(parent: parent1);
      child2Attachment.reparent(parent: parent1);
      child3Attachment.reparent(parent: parent2);
      child4Attachment.reparent(parent: parent2);
      child4.requestFocus();
      await tester.pump();
      final String description = debugDescribeFocusTree();
      expect(
        description,
        equalsIgnoringHashCodes(
          'FocusManager#00000\n'
1230
          ' │ primaryFocus: FocusNode#00000(Child 4 [PRIMARY FOCUS])\n'
1231 1232
          ' │ primaryFocusCreator: Container-[GlobalKey#00000] ← [root]\n'
          ' │\n'
1233
          ' └─rootScope: FocusScopeNode#00000(Root Focus Scope [IN FOCUS PATH])\n'
1234
          '   │ IN FOCUS PATH\n'
1235
          '   │ focusedChildren: FocusScopeNode#00000([IN FOCUS PATH])\n'
1236
          '   │\n'
1237
          '   ├─Child 1: FocusScopeNode#00000(Scope 1)\n'
1238 1239
          '   │ │ context: Container-[GlobalKey#00000]\n'
          '   │ │\n'
1240
          '   │ └─Child 1: FocusNode#00000(Parent 1)\n'
1241 1242
          '   │   │ context: Container-[GlobalKey#00000]\n'
          '   │   │\n'
1243
          '   │   ├─Child 1: FocusNode#00000(Child 1)\n'
1244 1245 1246 1247 1248
          '   │   │   context: Container-[GlobalKey#00000]\n'
          '   │   │\n'
          '   │   └─Child 2: FocusNode#00000\n'
          '   │       context: Container-[GlobalKey#00000]\n'
          '   │\n'
1249
          '   └─Child 2: FocusScopeNode#00000([IN FOCUS PATH])\n'
1250
          '     │ context: Container-[GlobalKey#00000]\n'
1251
          '     │ IN FOCUS PATH\n'
1252
          '     │ focusedChildren: FocusNode#00000(Child 4 [PRIMARY FOCUS])\n'
1253
          '     │\n'
1254
          '     └─Child 1: FocusNode#00000(Parent 2 [IN FOCUS PATH])\n'
1255
          '       │ context: Container-[GlobalKey#00000]\n'
1256
          '       │ IN FOCUS PATH\n'
1257
          '       │\n'
1258
          '       ├─Child 1: FocusNode#00000(Child 3)\n'
1259 1260
          '       │   context: Container-[GlobalKey#00000]\n'
          '       │\n'
1261
          '       └─Child 2: FocusNode#00000(Child 4 [PRIMARY FOCUS])\n'
1262
          '           context: Container-[GlobalKey#00000]\n'
1263 1264 1265
          '           PRIMARY FOCUS\n',
        ),
      );
1266 1267
    });
  });
1268

1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410

  group('Autofocus', () {
    testWidgets(
      'works when the previous focused node is detached',
      (WidgetTester tester) async {
        final FocusNode node1 = FocusNode();
        final FocusNode node2 = FocusNode();

        await tester.pumpWidget(
          FocusScope(
            child: Focus(autofocus: true, focusNode: node1, child: const Placeholder()),
          ),
        );
        await tester.pump();
        expect(node1.hasPrimaryFocus, isTrue);

        await tester.pumpWidget(
          FocusScope(
            child: SizedBox(
              child: Focus(autofocus: true, focusNode: node2, child: const Placeholder()),
            ),
          ),
        );
        await tester.pump();
        expect(node2.hasPrimaryFocus, isTrue);
    });

    testWidgets(
      'node detached before autofocus is applied',
      (WidgetTester tester) async {
        final FocusScopeNode scopeNode = FocusScopeNode();
        final FocusNode node1 = FocusNode();

        await tester.pumpWidget(
          FocusScope(
            node: scopeNode,
            child: Focus(
              autofocus: true,
              focusNode: node1,
              child: const Placeholder(),
            ),
          ),
        );
        await tester.pumpWidget(
          FocusScope(
            node: scopeNode,
            child: const Focus(child: Placeholder()),
          ),
        );

        await tester.pump();
        expect(node1.hasPrimaryFocus, isFalse);
        expect(scopeNode.hasPrimaryFocus, isTrue);
    });

    testWidgets('autofocus the first candidate', (WidgetTester tester) async {
      final FocusNode node1 = FocusNode();
      final FocusNode node2 = FocusNode();
      final FocusNode node3 = FocusNode();

      await tester.pumpWidget(
        Directionality(
          textDirection: TextDirection.ltr,
          child: Column(
            children: <Focus>[
              Focus(
                autofocus: true,
                focusNode: node1,
                child: const SizedBox(),
              ),
              Focus(
                autofocus: true,
                focusNode: node2,
                child: const SizedBox(),
              ),
              Focus(
                autofocus: true,
                focusNode: node3,
                child: const SizedBox(),
              ),
            ],
          ),
        ),
      );

      expect(node1.hasPrimaryFocus, isTrue);
    });

    testWidgets('Autofocus works with global key reparenting', (WidgetTester tester) async {
      final FocusNode node = FocusNode();
      final FocusScopeNode scope1 = FocusScopeNode(debugLabel: 'scope1');
      final FocusScopeNode scope2 = FocusScopeNode(debugLabel: 'scope2');
      final GlobalKey key = GlobalKey();

      await tester.pumpWidget(
        Directionality(
          textDirection: TextDirection.ltr,
          child: Column(
            children: <Focus>[
              FocusScope(
                node: scope1,
                child: Focus(
                  key: key,
                  focusNode: node,
                  child: const SizedBox(),
                ),
              ),
              FocusScope(node: scope2, child: const SizedBox()),
            ],
          ),
        ),
      );

      // _applyFocusChange will be called before persistentCallbacks,
      // guaranteeing the focus changes are applied before the BuildContext
      // `node` attaches to gets reparented.
      scope1.autofocus(node);

      await tester.pumpWidget(
        Directionality(
          textDirection: TextDirection.ltr,
          child: Column(
            children: <Focus>[
              FocusScope(node: scope1, child: const SizedBox()),
              FocusScope(
                node: scope2,
                child: Focus(
                  key: key,
                  focusNode: node,
                  child: const SizedBox(),
                ),
              ),
            ],
          ),
        ),
      );

      expect(node.hasPrimaryFocus, isTrue);
      expect(scope2.hasFocus, isTrue);
    });
  });

1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435
  testWidgets("Doesn't lose focused child when reparenting if the nearestScope doesn't change.", (WidgetTester tester) async {
    final BuildContext context = await setupWidget(tester);
    final FocusScopeNode parent1 = FocusScopeNode(debugLabel: 'parent1');
    final FocusScopeNode parent2 = FocusScopeNode(debugLabel: 'parent2');
    final FocusAttachment parent1Attachment = parent1.attach(context);
    final FocusAttachment parent2Attachment = parent2.attach(context);
    final FocusNode child1 = FocusNode(debugLabel: 'child1');
    final FocusAttachment child1Attachment = child1.attach(context);
    final FocusNode child2 = FocusNode(debugLabel: 'child2');
    final FocusAttachment child2Attachment = child2.attach(context);
    parent1Attachment.reparent(parent: tester.binding.focusManager.rootScope);
    child1Attachment.reparent(parent: parent1);
    child2Attachment.reparent(parent: child1);
    parent1.autofocus(child2);
    await tester.pump();
    parent2Attachment.reparent(parent: tester.binding.focusManager.rootScope);
    parent2.requestFocus();
    await tester.pump();
    expect(parent1.focusedChild, equals(child2));
    child2Attachment.reparent(parent: parent1);
    expect(parent1.focusedChild, equals(child2));
    parent1.requestFocus();
    await tester.pump();
    expect(parent1.focusedChild, equals(child2));
  });
1436

1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512
  testWidgets('Ancestors get notified exactly as often as needed if focused child changes focus.', (WidgetTester tester) async {
    bool topFocus = false;
    bool parent1Focus = false;
    bool parent2Focus = false;
    bool child1Focus = false;
    bool child2Focus = false;
    int topNotify = 0;
    int parent1Notify = 0;
    int parent2Notify = 0;
    int child1Notify = 0;
    int child2Notify = 0;
    void clear() {
      topFocus = false;
      parent1Focus = false;
      parent2Focus = false;
      child1Focus = false;
      child2Focus = false;
      topNotify = 0;
      parent1Notify = 0;
      parent2Notify = 0;
      child1Notify = 0;
      child2Notify = 0;
    }
    final BuildContext context = await setupWidget(tester);
    final FocusScopeNode top = FocusScopeNode(debugLabel: 'top');
    final FocusAttachment topAttachment = top.attach(context);
    final FocusScopeNode parent1 = FocusScopeNode(debugLabel: 'parent1');
    final FocusAttachment parent1Attachment = parent1.attach(context);
    final FocusScopeNode parent2 = FocusScopeNode(debugLabel: 'parent2');
    final FocusAttachment parent2Attachment = parent2.attach(context);
    final FocusNode child1 = FocusNode(debugLabel: 'child1');
    final FocusAttachment child1Attachment = child1.attach(context);
    final FocusNode child2 = FocusNode(debugLabel: 'child2');
    final FocusAttachment child2Attachment = child2.attach(context);
    topAttachment.reparent(parent: tester.binding.focusManager.rootScope);
    parent1Attachment.reparent(parent: top);
    parent2Attachment.reparent(parent: top);
    child1Attachment.reparent(parent: parent1);
    child2Attachment.reparent(parent: parent2);
    top.addListener(() {
      topNotify++;
      topFocus = top.hasFocus;
    });
    parent1.addListener(() {
      parent1Notify++;
      parent1Focus = parent1.hasFocus;
    });
    parent2.addListener(() {
      parent2Notify++;
      parent2Focus = parent2.hasFocus;
    });
    child1.addListener(() {
      child1Notify++;
      child1Focus = child1.hasFocus;
    });
    child2.addListener(() {
      child2Notify++;
      child2Focus = child2.hasFocus;
    });
    child1.requestFocus();
    await tester.pump();
    expect(topFocus, isTrue);
    expect(parent1Focus, isTrue);
    expect(child1Focus, isTrue);
    expect(parent2Focus, isFalse);
    expect(child2Focus, isFalse);
    expect(topNotify, equals(1));
    expect(parent1Notify, equals(1));
    expect(child1Notify, equals(1));
    expect(parent2Notify, equals(0));
    expect(child2Notify, equals(0));

    clear();
    child1.unfocus();
    await tester.pump();
    expect(topFocus, isFalse);
1513
    expect(parent1Focus, isTrue);
1514 1515 1516
    expect(child1Focus, isFalse);
    expect(parent2Focus, isFalse);
    expect(child2Focus, isFalse);
1517
    expect(topNotify, equals(0));
1518 1519 1520 1521 1522 1523 1524 1525
    expect(parent1Notify, equals(1));
    expect(child1Notify, equals(1));
    expect(parent2Notify, equals(0));
    expect(child2Notify, equals(0));

    clear();
    child1.requestFocus();
    await tester.pump();
1526
    expect(topFocus, isFalse);
1527 1528 1529 1530
    expect(parent1Focus, isTrue);
    expect(child1Focus, isTrue);
    expect(parent2Focus, isFalse);
    expect(child2Focus, isFalse);
1531
    expect(topNotify, equals(0));
1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566
    expect(parent1Notify, equals(1));
    expect(child1Notify, equals(1));
    expect(parent2Notify, equals(0));
    expect(child2Notify, equals(0));

    clear();
    child2.requestFocus();
    await tester.pump();
    expect(topFocus, isFalse);
    expect(parent1Focus, isFalse);
    expect(child1Focus, isFalse);
    expect(parent2Focus, isTrue);
    expect(child2Focus, isTrue);
    expect(topNotify, equals(0));
    expect(parent1Notify, equals(1));
    expect(child1Notify, equals(1));
    expect(parent2Notify, equals(1));
    expect(child2Notify, equals(1));

    // Changing the focus back before the pump shouldn't cause notifications.
    clear();
    child1.requestFocus();
    child2.requestFocus();
    await tester.pump();
    expect(topFocus, isFalse);
    expect(parent1Focus, isFalse);
    expect(child1Focus, isFalse);
    expect(parent2Focus, isFalse);
    expect(child2Focus, isFalse);
    expect(topNotify, equals(0));
    expect(parent1Notify, equals(0));
    expect(child1Notify, equals(0));
    expect(parent2Notify, equals(0));
    expect(child2Notify, equals(0));
  });
1567

1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 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
  testWidgets('Focus changes notify listeners.', (WidgetTester tester) async {
    final BuildContext context = await setupWidget(tester);
    final FocusScopeNode parent1 = FocusScopeNode(debugLabel: 'parent1');
    final FocusAttachment parent1Attachment = parent1.attach(context);
    final FocusNode child1 = FocusNode(debugLabel: 'child1');
    final FocusAttachment child1Attachment = child1.attach(context);
    final FocusNode child2 = FocusNode(debugLabel: 'child2');
    final FocusAttachment child2Attachment = child2.attach(context);
    parent1Attachment.reparent(parent: tester.binding.focusManager.rootScope);
    child1Attachment.reparent(parent: parent1);
    child2Attachment.reparent(parent: child1);

    int notifyCount = 0;
    void handleFocusChange() {
      notifyCount++;
    }
    tester.binding.focusManager.addListener(handleFocusChange);

    parent1.autofocus(child2);
    expect(notifyCount, equals(0));
    await tester.pump();
    expect(notifyCount, equals(1));
    notifyCount = 0;

    child1.requestFocus();
    child2.requestFocus();
    child1.requestFocus();
    await tester.pump();
    expect(notifyCount, equals(1));
    notifyCount = 0;

    child2.requestFocus();
    await tester.pump();
    expect(notifyCount, equals(1));
    notifyCount = 0;

    child2.unfocus();
    await tester.pump();
    expect(notifyCount, equals(1));
    notifyCount = 0;

    tester.binding.focusManager.removeListener(handleFocusChange);
  });
1611

1612 1613 1614 1615 1616 1617 1618 1619 1620 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 1649 1650 1651 1652 1653 1654 1655 1656
  testWidgets('FocusManager notifies listeners when a widget loses focus because it was removed.', (WidgetTester tester) async {
    final FocusNode nodeA = FocusNode(debugLabel: 'a');
    final FocusNode nodeB = FocusNode(debugLabel: 'b');
    await tester.pumpWidget(
      Directionality(
        textDirection: TextDirection.rtl,
        child: Column(
          children: <Widget>[
            Focus(focusNode: nodeA , child: const Text('a')),
            Focus(focusNode: nodeB, child: const Text('b')),
          ],
        ),
      ),
    );
    int notifyCount = 0;
    void handleFocusChange() {
      notifyCount++;
    }
    tester.binding.focusManager.addListener(handleFocusChange);

    nodeA.requestFocus();
    await tester.pump();
    expect(nodeA.hasPrimaryFocus, isTrue);
    expect(notifyCount, equals(1));
    notifyCount = 0;

    await tester.pumpWidget(
      Directionality(
        textDirection: TextDirection.rtl,
        child: Column(
          children: <Widget>[
            Focus(focusNode: nodeB, child: const Text('b')),
          ],
        ),
      ),
    );

    await tester.pump();
    expect(nodeA.hasPrimaryFocus, isFalse);
    expect(nodeB.hasPrimaryFocus, isFalse);
    expect(notifyCount, equals(1));
    notifyCount = 0;

    tester.binding.focusManager.removeListener(handleFocusChange);
  });
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 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699

  testWidgets('debugFocusChanges causes logging of focus changes', (WidgetTester tester) async {
    final bool oldDebugFocusChanges = debugFocusChanges;
    final DebugPrintCallback oldDebugPrint = debugPrint;
    final StringBuffer messages = StringBuffer();
    debugPrint = (String? message, {int? wrapWidth}) {
      messages.writeln(message ?? '');
    };
    debugFocusChanges = true;
    try {
      final BuildContext context = await setupWidget(tester);
      final FocusScopeNode parent1 = FocusScopeNode(debugLabel: 'parent1');
      final FocusAttachment parent1Attachment = parent1.attach(context);
      final FocusNode child1 = FocusNode(debugLabel: 'child1');
      final FocusAttachment child1Attachment = child1.attach(context);
      parent1Attachment.reparent(parent: tester.binding.focusManager.rootScope);
      child1Attachment.reparent(parent: parent1);

      int notifyCount = 0;
      void handleFocusChange() {
        notifyCount++;
      }
      tester.binding.focusManager.addListener(handleFocusChange);

      parent1.requestFocus();
      expect(notifyCount, equals(0));
      await tester.pump();
      expect(notifyCount, equals(1));
      notifyCount = 0;

      child1.requestFocus();
      await tester.pump();
      expect(notifyCount, equals(1));
      notifyCount = 0;

      tester.binding.focusManager.removeListener(handleFocusChange);
    } finally {
      debugFocusChanges = oldDebugFocusChanges;
      debugPrint = oldDebugPrint;
    }
    final String messagesStr = messages.toString();
    expect(messagesStr.split('\n').length, equals(58));
    expect(messagesStr, contains(RegExp(r'   └─Child 1: FocusScopeNode#[a-f0-9]{5}\(parent1 \[PRIMARY FOCUS\]\)')));
1700
    expect(messagesStr, contains('FOCUS: Notified 2 dirty nodes'));
1701 1702
    expect(messagesStr, contains(RegExp(r'FOCUS: Scheduling update, current focus is null, next focus will be FocusScopeNode#.*parent1')));
  });
1703
}