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

5
import 'package:flutter/foundation.dart';
6
import 'package:flutter/gestures.dart';
7
import 'package:flutter/material.dart';
8
import 'package:flutter/rendering.dart';
9
import 'package:flutter/services.dart';
10 11
import 'package:flutter_test/flutter_test.dart';

12 13
typedef ElementRebuildCallback = void Function(StatefulElement element);

14 15
class TestState extends State<StatefulWidget> {
  @override
16
  Widget build(BuildContext context) => const SizedBox();
17 18
}

19 20
@optionalTypeArgs
class _MyGlobalObjectKey<T extends State<StatefulWidget>> extends GlobalObjectKey<T> {
21
  const _MyGlobalObjectKey(super.value);
22 23
}

24 25
void main() {
  testWidgets('UniqueKey control test', (WidgetTester tester) async {
26
    final Key key = UniqueKey();
27
    expect(key, hasOneLineDescription);
28
    expect(key, isNot(equals(UniqueKey())));
29 30 31
  });

  testWidgets('ObjectKey control test', (WidgetTester tester) async {
32 33 34 35 36
    final Object a = Object();
    final Object b = Object();
    final Key keyA = ObjectKey(a);
    final Key keyA2 = ObjectKey(a);
    final Key keyB = ObjectKey(b);
37 38 39 40 41 42 43

    expect(keyA, hasOneLineDescription);
    expect(keyA, equals(keyA2));
    expect(keyA.hashCode, equals(keyA2.hashCode));
    expect(keyA, isNot(equals(keyB)));
  });

44
  testWidgets('GlobalObjectKey toString test', (WidgetTester tester) async {
45 46 47 48
    const GlobalObjectKey one = GlobalObjectKey(1);
    const GlobalObjectKey<TestState> two = GlobalObjectKey<TestState>(2);
    const GlobalObjectKey three = _MyGlobalObjectKey(3);
    const GlobalObjectKey<TestState> four = _MyGlobalObjectKey<TestState>(4);
49 50 51 52 53 54 55

    expect(one.toString(), equals('[GlobalObjectKey ${describeIdentity(1)}]'));
    expect(two.toString(), equals('[GlobalObjectKey<TestState> ${describeIdentity(2)}]'));
    expect(three.toString(), equals('[_MyGlobalObjectKey ${describeIdentity(3)}]'));
    expect(four.toString(), equals('[_MyGlobalObjectKey<TestState> ${describeIdentity(4)}]'));
  });

56
  testWidgets('GlobalObjectKey control test', (WidgetTester tester) async {
57 58 59 60 61
    final Object a = Object();
    final Object b = Object();
    final Key keyA = GlobalObjectKey(a);
    final Key keyA2 = GlobalObjectKey(a);
    final Key keyB = GlobalObjectKey(b);
62 63 64 65 66 67 68

    expect(keyA, hasOneLineDescription);
    expect(keyA, equals(keyA2));
    expect(keyA.hashCode, equals(keyA2.hashCode));
    expect(keyA, isNot(equals(keyB)));
  });

69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 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
  testWidgets('GlobalKey correct case 1 - can move global key from container widget to layoutbuilder', (WidgetTester tester) async {
    final Key key = GlobalKey(debugLabel: 'correct');
    await tester.pumpWidget(Stack(
      textDirection: TextDirection.ltr,
      children: <Widget>[
        Container(
          key: const ValueKey<int>(1),
          child: SizedBox(key: key),
        ),
        LayoutBuilder(
          key: const ValueKey<int>(2),
          builder: (BuildContext context, BoxConstraints constraints) {
            return const Placeholder();
          },
        ),
      ],
    ));

    await tester.pumpWidget(Stack(
      textDirection: TextDirection.ltr,
      children: <Widget>[
        Container(
          key: const ValueKey<int>(1),
          child: const Placeholder(),
        ),
        LayoutBuilder(
          key: const ValueKey<int>(2),
          builder: (BuildContext context, BoxConstraints constraints) {
            return SizedBox(key: key);
          },
        ),
      ],
    ));
  });

  testWidgets('GlobalKey correct case 2 - can move global key from layoutbuilder to container widget', (WidgetTester tester) async {
    final Key key = GlobalKey(debugLabel: 'correct');
    await tester.pumpWidget(Stack(
      textDirection: TextDirection.ltr,
      children: <Widget>[
        Container(
          key: const ValueKey<int>(1),
          child: const Placeholder(),
        ),
        LayoutBuilder(
          key: const ValueKey<int>(2),
          builder: (BuildContext context, BoxConstraints constraints) {
            return SizedBox(key: key);
          },
        ),
      ],
    ));
    await tester.pumpWidget(Stack(
      textDirection: TextDirection.ltr,
      children: <Widget>[
        Container(
          key: const ValueKey<int>(1),
          child: SizedBox(key: key),
        ),
        LayoutBuilder(
          key: const ValueKey<int>(2),
          builder: (BuildContext context, BoxConstraints constraints) {
            return const Placeholder();
          },
        ),
      ],
    ));
  });

  testWidgets('GlobalKey correct case 3 - can deal with early rebuild in layoutbuilder - move backward', (WidgetTester tester) async {
    const Key key1 = GlobalObjectKey('Text1');
    const Key key2 = GlobalObjectKey('Text2');
141 142 143
    Key? rebuiltKeyOfSecondChildBeforeLayout;
    Key? rebuiltKeyOfFirstChildAfterLayout;
    Key? rebuiltKeyOfSecondChildAfterLayout;
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
    await tester.pumpWidget(
      LayoutBuilder(
        builder: (BuildContext context, BoxConstraints constraints) {
          return Column(
            children: <Widget>[
              const _Stateful(
                child: Text(
                  'Text1',
                  textDirection: TextDirection.ltr,
                  key: key1,
                ),
              ),
              _Stateful(
                child: const Text(
                  'Text2',
                  textDirection: TextDirection.ltr,
                  key: key2,
                ),
                onElementRebuild: (StatefulElement element) {
                  // We don't want noise to override the result;
                  expect(rebuiltKeyOfSecondChildBeforeLayout, isNull);
                  final _Stateful statefulWidget = element.widget as _Stateful;
                  rebuiltKeyOfSecondChildBeforeLayout =
                    statefulWidget.child.key;
                },
              ),
            ],
          );
        },
173
      ),
174 175 176 177 178 179 180 181 182 183 184 185 186 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 218 219
    );
    // Result will be written during first build and need to clear it to remove
    // noise.
    rebuiltKeyOfSecondChildBeforeLayout = null;

    final _StatefulState state = tester.firstState(find.byType(_Stateful).at(1));
    state.rebuild();
    // Reorders the items
    await tester.pumpWidget(
      LayoutBuilder(
        builder: (BuildContext context, BoxConstraints constraints) {
          return Column(
            children: <Widget>[
              _Stateful(
                child: const Text(
                  'Text2',
                  textDirection: TextDirection.ltr,
                  key: key2,
                ),
                onElementRebuild: (StatefulElement element) {
                  // Verifies the early rebuild happens before layout.
                  expect(rebuiltKeyOfSecondChildBeforeLayout, key2);
                  // We don't want noise to override the result;
                  expect(rebuiltKeyOfFirstChildAfterLayout, isNull);
                  final _Stateful statefulWidget = element.widget as _Stateful;
                  rebuiltKeyOfFirstChildAfterLayout = statefulWidget.child.key;
                },
              ),
              _Stateful(
                child: const Text(
                  'Text1',
                  textDirection: TextDirection.ltr,
                  key: key1,
                ),
                onElementRebuild: (StatefulElement element) {
                  // Verifies the early rebuild happens before layout.
                  expect(rebuiltKeyOfSecondChildBeforeLayout, key2);
                  // We don't want noise to override the result;
                  expect(rebuiltKeyOfSecondChildAfterLayout, isNull);
                  final _Stateful statefulWidget = element.widget as _Stateful;
                  rebuiltKeyOfSecondChildAfterLayout = statefulWidget.child.key;
                },
              ),
            ],
          );
        },
220
      ),
221 222 223 224 225 226 227 228 229 230
    );
    expect(rebuiltKeyOfSecondChildBeforeLayout, key2);
    expect(rebuiltKeyOfFirstChildAfterLayout, key2);
    expect(rebuiltKeyOfSecondChildAfterLayout, key1);
  });

  testWidgets('GlobalKey correct case 4 - can deal with early rebuild in layoutbuilder - move forward', (WidgetTester tester) async {
    const Key key1 = GlobalObjectKey('Text1');
    const Key key2 = GlobalObjectKey('Text2');
    const Key key3 = GlobalObjectKey('Text3');
231 232 233
    Key? rebuiltKeyOfSecondChildBeforeLayout;
    Key? rebuiltKeyOfSecondChildAfterLayout;
    Key? rebuiltKeyOfThirdChildAfterLayout;
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
    await tester.pumpWidget(
      LayoutBuilder(
        builder: (BuildContext context, BoxConstraints constraints) {
          return Column(
            children: <Widget>[
              const _Stateful(
                child: Text(
                  'Text1',
                  textDirection: TextDirection.ltr,
                  key: key1,
                ),
              ),
              _Stateful(
                child: const Text(
                  'Text2',
                  textDirection: TextDirection.ltr,
                  key: key2,
                ),
                onElementRebuild: (StatefulElement element) {
                  // We don't want noise to override the result;
                  expect(rebuiltKeyOfSecondChildBeforeLayout, isNull);
                  final _Stateful statefulWidget = element.widget as _Stateful;
                  rebuiltKeyOfSecondChildBeforeLayout = statefulWidget.child.key;
                },
              ),
              const _Stateful(
                child: Text(
                  'Text3',
                  textDirection: TextDirection.ltr,
                  key: key3,
                ),
              ),
            ],
          );
        },
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
    );
    // Result will be written during first build and need to clear it to remove
    // noise.
    rebuiltKeyOfSecondChildBeforeLayout = null;

    final _StatefulState state = tester.firstState(find.byType(_Stateful).at(1));
    state.rebuild();
    // Reorders the items
    await tester.pumpWidget(
      LayoutBuilder(
        builder: (BuildContext context, BoxConstraints constraints) {
          return Column(
            children: <Widget>[
              const _Stateful(
                child: Text(
                  'Text1',
                  textDirection: TextDirection.ltr,
                  key: key1,
                ),
              ),
              _Stateful(
                child: const Text(
                  'Text3',
                  textDirection: TextDirection.ltr,
                  key: key3,
                ),
                onElementRebuild: (StatefulElement element) {
                  // Verifies the early rebuild happens before layout.
                  expect(rebuiltKeyOfSecondChildBeforeLayout, key2);
                  // We don't want noise to override the result;
                  expect(rebuiltKeyOfSecondChildAfterLayout, isNull);
                  final _Stateful statefulWidget = element.widget as _Stateful;
                  rebuiltKeyOfSecondChildAfterLayout = statefulWidget.child.key;
                },
              ),
              _Stateful(
                child: const Text(
                  'Text2',
                  textDirection: TextDirection.ltr,
                  key: key2,
                ),
                onElementRebuild: (StatefulElement element) {
                  // Verifies the early rebuild happens before layout.
                  expect(rebuiltKeyOfSecondChildBeforeLayout, key2);
                  // We don't want noise to override the result;
                  expect(rebuiltKeyOfThirdChildAfterLayout, isNull);
                  final _Stateful statefulWidget = element.widget as _Stateful;
                  rebuiltKeyOfThirdChildAfterLayout = statefulWidget.child.key;
                },
              ),
            ],
          );
        },
323
      ),
324 325 326 327 328 329 330 331
    );
    expect(rebuiltKeyOfSecondChildBeforeLayout, key2);
    expect(rebuiltKeyOfSecondChildAfterLayout, key3);
    expect(rebuiltKeyOfThirdChildAfterLayout, key2);
  });

  testWidgets('GlobalKey correct case 5 - can deal with early rebuild in layoutbuilder - only one global key', (WidgetTester tester) async {
    const Key key1 = GlobalObjectKey('Text1');
332 333
    Key? rebuiltKeyOfSecondChildBeforeLayout;
    Key? rebuiltKeyOfThirdChildAfterLayout;
334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
    await tester.pumpWidget(
      LayoutBuilder(
        builder: (BuildContext context, BoxConstraints constraints) {
          return Column(
            children: <Widget>[
              const _Stateful(
                child: Text(
                  'Text1',
                  textDirection: TextDirection.ltr,
                ),
              ),
              _Stateful(
                child: const Text(
                  'Text2',
                  textDirection: TextDirection.ltr,
                  key: key1,
                ),
                onElementRebuild: (StatefulElement element) {
                  // We don't want noise to override the result;
                  expect(rebuiltKeyOfSecondChildBeforeLayout, isNull);
                  final _Stateful statefulWidget = element.widget as _Stateful;
                  rebuiltKeyOfSecondChildBeforeLayout = statefulWidget.child.key;
                },
              ),
              const _Stateful(
                child: Text(
                  'Text3',
                  textDirection: TextDirection.ltr,
                ),
              ),
            ],
          );
        },
367
      ),
368 369 370 371 372 373 374 375 376 377 378 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
    );
    // Result will be written during first build and need to clear it to remove
    // noise.
    rebuiltKeyOfSecondChildBeforeLayout = null;

    final _StatefulState state = tester.firstState(find.byType(_Stateful).at(1));
    state.rebuild();
    // Reorders the items
    await tester.pumpWidget(
      LayoutBuilder(
        builder: (BuildContext context, BoxConstraints constraints) {
          return Column(
            children: <Widget>[
              const _Stateful(
                child: Text(
                  'Text1',
                  textDirection: TextDirection.ltr,
                ),
              ),
              _Stateful(
                child: const Text(
                  'Text3',
                  textDirection: TextDirection.ltr,
                ),
                onElementRebuild: (StatefulElement element) {
                  // Verifies the early rebuild happens before layout.
                  expect(rebuiltKeyOfSecondChildBeforeLayout, key1);
                },
              ),
              _Stateful(
                child: const Text(
                  'Text2',
                  textDirection: TextDirection.ltr,
                  key: key1,
                ),
                onElementRebuild: (StatefulElement element) {
                  // Verifies the early rebuild happens before layout.
                  expect(rebuiltKeyOfSecondChildBeforeLayout, key1);
                  // We don't want noise to override the result;
                  expect(rebuiltKeyOfThirdChildAfterLayout, isNull);
                  final _Stateful statefulWidget = element.widget as _Stateful;
                  rebuiltKeyOfThirdChildAfterLayout = statefulWidget.child.key;
                },
              ),
            ],
          );
        },
415
      ),
416 417 418 419 420
    );
    expect(rebuiltKeyOfSecondChildBeforeLayout, key1);
    expect(rebuiltKeyOfThirdChildAfterLayout, key1);
  });

421
  testWidgets('GlobalKey duplication 1 - double appearance', (WidgetTester tester) async {
422 423
    final Key key = GlobalKey(debugLabel: 'problematic');
    await tester.pumpWidget(Stack(
424
      textDirection: TextDirection.ltr,
425
      children: <Widget>[
426
        Container(
427
          key: const ValueKey<int>(1),
428
          child: SizedBox(key: key),
429
        ),
430
        Container(
431
          key: const ValueKey<int>(2),
432
          child: Placeholder(key: key),
433 434 435
        ),
      ],
    ));
436 437 438 439 440 441 442 443 444
    final dynamic exception = tester.takeException();
    expect(exception, isFlutterError);
    expect(
      exception.toString(),
      equalsIgnoringHashCodes(
        'Multiple widgets used the same GlobalKey.\n'
        'The key [GlobalKey#00000 problematic] was used by multiple widgets. The parents of those widgets were:\n'
        '- Container-[<1>]\n'
        '- Container-[<2>]\n'
445
        'A GlobalKey can only be specified on one widget at a time in the widget tree.',
446 447
      ),
    );
448 449 450
  });

  testWidgets('GlobalKey duplication 2 - splitting and changing type', (WidgetTester tester) async {
451
    final Key key = GlobalKey(debugLabel: 'problematic');
452

453
    await tester.pumpWidget(Stack(
454
      textDirection: TextDirection.ltr,
455
      children: <Widget>[
456
        Container(
457 458
          key: const ValueKey<int>(1),
        ),
459
        Container(
460 461
          key: const ValueKey<int>(2),
        ),
462
        Container(
463
          key: key,
464 465 466 467
        ),
      ],
    ));

468
    await tester.pumpWidget(Stack(
469
      textDirection: TextDirection.ltr,
470
      children: <Widget>[
471
        Container(
472
          key: const ValueKey<int>(1),
473
          child: SizedBox(key: key),
474
        ),
475
        Container(
476
          key: const ValueKey<int>(2),
477
          child: Placeholder(key: key),
478 479 480 481
        ),
      ],
    ));

482 483 484 485 486 487 488 489 490
    final dynamic exception = tester.takeException();
    expect(exception, isFlutterError);
    expect(
      exception.toString(),
      equalsIgnoringHashCodes(
        'Multiple widgets used the same GlobalKey.\n'
        'The key [GlobalKey#00000 problematic] was used by multiple widgets. The parents of those widgets were:\n'
        '- Container-[<1>]\n'
        '- Container-[<2>]\n'
491
        'A GlobalKey can only be specified on one widget at a time in the widget tree.',
492
      ),
493
    );
494 495
  });

496
  testWidgets('GlobalKey duplication 3 - splitting and changing type', (WidgetTester tester) async {
497 498
    final Key key = GlobalKey(debugLabel: 'problematic');
    await tester.pumpWidget(Stack(
499
      textDirection: TextDirection.ltr,
500
      children: <Widget>[
501
        Container(key: key),
502 503
      ],
    ));
504
    await tester.pumpWidget(Stack(
505
      textDirection: TextDirection.ltr,
506
      children: <Widget>[
507 508
        SizedBox(key: key),
        Placeholder(key: key),
509 510
      ],
    ));
511 512 513 514 515
    final dynamic exception = tester.takeException();
    expect(exception, isFlutterError);
    expect(
      exception.toString(),
      equalsIgnoringHashCodes(
516
        'Duplicate keys found.\n'
517
        'If multiple keyed widgets exist as children of another widget, they must have unique keys.\n'
518
        'Stack(alignment: AlignmentDirectional.topStart, textDirection: ltr, fit: loose) has multiple children with key [GlobalKey#00000 problematic].'
519
      ),
520
    );
521 522 523
  });

  testWidgets('GlobalKey duplication 4 - splitting and half changing type', (WidgetTester tester) async {
524 525
    final Key key = GlobalKey(debugLabel: 'problematic');
    await tester.pumpWidget(Stack(
526
      textDirection: TextDirection.ltr,
527
      children: <Widget>[
528
        Container(key: key),
529 530
      ],
    ));
531
    await tester.pumpWidget(Stack(
532
      textDirection: TextDirection.ltr,
533
      children: <Widget>[
534 535
        Container(key: key),
        Placeholder(key: key),
536 537
      ],
    ));
538 539 540 541 542
    final dynamic exception = tester.takeException();
    expect(exception, isFlutterError);
    expect(
      exception.toString(),
      equalsIgnoringHashCodes(
543
        'Duplicate keys found.\n'
544
        'If multiple keyed widgets exist as children of another widget, they must have unique keys.\n'
545
        'Stack(alignment: AlignmentDirectional.topStart, textDirection: ltr, fit: loose) has multiple children with key [GlobalKey#00000 problematic].'
546
      ),
547
    );
548 549 550
  });

  testWidgets('GlobalKey duplication 5 - splitting and half changing type', (WidgetTester tester) async {
551 552
    final Key key = GlobalKey(debugLabel: 'problematic');
    await tester.pumpWidget(Stack(
553
      textDirection: TextDirection.ltr,
554
      children: <Widget>[
555
        Container(key: key),
556 557
      ],
    ));
558
    await tester.pumpWidget(Stack(
559
      textDirection: TextDirection.ltr,
560
      children: <Widget>[
561 562
        Placeholder(key: key),
        Container(key: key),
563 564 565 566 567 568
      ],
    ));
    expect(tester.takeException(), isFlutterError);
  });

  testWidgets('GlobalKey duplication 6 - splitting and not changing type', (WidgetTester tester) async {
569 570
    final Key key = GlobalKey(debugLabel: 'problematic');
    await tester.pumpWidget(Stack(
571
      textDirection: TextDirection.ltr,
572
      children: <Widget>[
573
        Container(key: key),
574 575
      ],
    ));
576
    await tester.pumpWidget(Stack(
577
      textDirection: TextDirection.ltr,
578
      children: <Widget>[
579 580
        Container(key: key),
        Container(key: key),
581 582 583 584 585 586
      ],
    ));
    expect(tester.takeException(), isFlutterError);
  });

  testWidgets('GlobalKey duplication 7 - appearing later', (WidgetTester tester) async {
587 588
    final Key key = GlobalKey(debugLabel: 'problematic');
    await tester.pumpWidget(Stack(
589
      textDirection: TextDirection.ltr,
590
      children: <Widget>[
591 592
        Container(key: const ValueKey<int>(1), child: Container(key: key)),
        Container(key: const ValueKey<int>(2)),
593 594
      ],
    ));
595
    await tester.pumpWidget(Stack(
596
      textDirection: TextDirection.ltr,
597
      children: <Widget>[
598 599
        Container(key: const ValueKey<int>(1), child: Container(key: key)),
        Container(key: const ValueKey<int>(2), child: Container(key: key)),
600 601 602 603 604 605
      ],
    ));
    expect(tester.takeException(), isFlutterError);
  });

  testWidgets('GlobalKey duplication 8 - appearing earlier', (WidgetTester tester) async {
606 607
    final Key key = GlobalKey(debugLabel: 'problematic');
    await tester.pumpWidget(Stack(
608
      textDirection: TextDirection.ltr,
609
      children: <Widget>[
610 611
        Container(key: const ValueKey<int>(1)),
        Container(key: const ValueKey<int>(2), child: Container(key: key)),
612 613
      ],
    ));
614
    await tester.pumpWidget(Stack(
615
      textDirection: TextDirection.ltr,
616
      children: <Widget>[
617 618
        Container(key: const ValueKey<int>(1), child: Container(key: key)),
        Container(key: const ValueKey<int>(2), child: Container(key: key)),
619 620 621 622 623 624
      ],
    ));
    expect(tester.takeException(), isFlutterError);
  });

  testWidgets('GlobalKey duplication 9 - moving and appearing later', (WidgetTester tester) async {
625 626
    final Key key = GlobalKey(debugLabel: 'problematic');
    await tester.pumpWidget(Stack(
627
      textDirection: TextDirection.ltr,
628
      children: <Widget>[
629 630 631
        Container(key: const ValueKey<int>(0), child: Container(key: key)),
        Container(key: const ValueKey<int>(1)),
        Container(key: const ValueKey<int>(2)),
632 633
      ],
    ));
634
    await tester.pumpWidget(Stack(
635
      textDirection: TextDirection.ltr,
636
      children: <Widget>[
637 638 639
        Container(key: const ValueKey<int>(0)),
        Container(key: const ValueKey<int>(1), child: Container(key: key)),
        Container(key: const ValueKey<int>(2), child: Container(key: key)),
640 641 642 643 644 645
      ],
    ));
    expect(tester.takeException(), isFlutterError);
  });

  testWidgets('GlobalKey duplication 10 - moving and appearing earlier', (WidgetTester tester) async {
646 647
    final Key key = GlobalKey(debugLabel: 'problematic');
    await tester.pumpWidget(Stack(
648
      textDirection: TextDirection.ltr,
649
      children: <Widget>[
650 651 652
        Container(key: const ValueKey<int>(1)),
        Container(key: const ValueKey<int>(2)),
        Container(key: const ValueKey<int>(3), child: Container(key: key)),
653 654
      ],
    ));
655
    await tester.pumpWidget(Stack(
656
      textDirection: TextDirection.ltr,
657
      children: <Widget>[
658 659 660
        Container(key: const ValueKey<int>(1), child: Container(key: key)),
        Container(key: const ValueKey<int>(2), child: Container(key: key)),
        Container(key: const ValueKey<int>(3)),
661 662 663 664 665 666
      ],
    ));
    expect(tester.takeException(), isFlutterError);
  });

  testWidgets('GlobalKey duplication 11 - double sibling appearance', (WidgetTester tester) async {
667 668
    final Key key = GlobalKey(debugLabel: 'problematic');
    await tester.pumpWidget(Stack(
669
      textDirection: TextDirection.ltr,
670
      children: <Widget>[
671 672
        Container(key: key),
        Container(key: key),
673 674 675 676 677 678
      ],
    ));
    expect(tester.takeException(), isFlutterError);
  });

  testWidgets('GlobalKey duplication 12 - all kinds of badness at once', (WidgetTester tester) async {
679 680 681 682
    final Key key1 = GlobalKey(debugLabel: 'problematic');
    final Key key2 = GlobalKey(debugLabel: 'problematic'); // intentionally the same label
    final Key key3 = GlobalKey(debugLabel: 'also problematic');
    await tester.pumpWidget(Stack(
683
      textDirection: TextDirection.ltr,
684
      children: <Widget>[
685 686 687 688 689 690 691 692 693
        Container(key: key1),
        Container(key: key1),
        Container(key: key2),
        Container(key: key1),
        Container(key: key1),
        Container(key: key2),
        Container(key: key1),
        Container(key: key1),
        Row(
694
          children: <Widget>[
695 696 697 698 699 700 701
            Container(key: key1),
            Container(key: key1),
            Container(key: key2),
            Container(key: key2),
            Container(key: key2),
            Container(key: key3),
            Container(key: key2),
702 703
          ],
        ),
704
        Row(
705
          children: <Widget>[
706 707 708
            Container(key: key1),
            Container(key: key1),
            Container(key: key3),
709 710
          ],
        ),
711
        Container(key: key3),
712 713
      ],
    ));
714 715 716 717 718 719
    final dynamic exception = tester.takeException();
    expect(exception, isFlutterError);
    expect(
      exception.toString(),
      equalsIgnoringHashCodes(
        'Duplicate keys found.\n'
720
        'If multiple keyed widgets exist as children of another widget, they must have unique keys.\n'
721
        'Stack(alignment: AlignmentDirectional.topStart, textDirection: ltr, fit: loose) has multiple children with key [GlobalKey#00000 problematic].',
722 723
      ),
    );
724 725 726
  });

  testWidgets('GlobalKey duplication 13 - all kinds of badness at once', (WidgetTester tester) async {
727 728 729 730
    final Key key1 = GlobalKey(debugLabel: 'problematic');
    final Key key2 = GlobalKey(debugLabel: 'problematic'); // intentionally the same label
    final Key key3 = GlobalKey(debugLabel: 'also problematic');
    await tester.pumpWidget(Stack(
731
      textDirection: TextDirection.ltr,
732
      children: <Widget>[
733 734 735
        Container(key: key1),
        Container(key: key2),
        Container(key: key3),
736 737
      ],
    ));
738
    await tester.pumpWidget(Stack(
739
      textDirection: TextDirection.ltr,
740
      children: <Widget>[
741 742 743 744 745 746 747 748 749
        Container(key: key1),
        Container(key: key1),
        Container(key: key2),
        Container(key: key1),
        Container(key: key1),
        Container(key: key2),
        Container(key: key1),
        Container(key: key1),
        Row(
750
          children: <Widget>[
751 752 753 754 755 756 757
            Container(key: key1),
            Container(key: key1),
            Container(key: key2),
            Container(key: key2),
            Container(key: key2),
            Container(key: key3),
            Container(key: key2),
758 759
          ],
        ),
760
        Row(
761
          children: <Widget>[
762 763 764
            Container(key: key1),
            Container(key: key1),
            Container(key: key3),
765 766
          ],
        ),
767
        Container(key: key3),
768 769 770 771 772 773
      ],
    ));
    expect(tester.takeException(), isFlutterError);
  });

  testWidgets('GlobalKey duplication 14 - moving during build - before', (WidgetTester tester) async {
774 775
    final Key key = GlobalKey(debugLabel: 'problematic');
    await tester.pumpWidget(Stack(
776
      textDirection: TextDirection.ltr,
777
      children: <Widget>[
778 779 780
        Container(key: key),
        Container(key: const ValueKey<int>(0)),
        Container(key: const ValueKey<int>(1)),
781 782
      ],
    ));
783
    await tester.pumpWidget(Stack(
784
      textDirection: TextDirection.ltr,
785
      children: <Widget>[
786 787
        Container(key: const ValueKey<int>(0)),
        Container(key: const ValueKey<int>(1), child: Container(key: key)),
788 789 790 791 792
      ],
    ));
  });

  testWidgets('GlobalKey duplication 15 - duplicating during build - before', (WidgetTester tester) async {
793 794
    final Key key = GlobalKey(debugLabel: 'problematic');
    await tester.pumpWidget(Stack(
795
      textDirection: TextDirection.ltr,
796
      children: <Widget>[
797 798 799
        Container(key: key),
        Container(key: const ValueKey<int>(0)),
        Container(key: const ValueKey<int>(1)),
800 801
      ],
    ));
802
    await tester.pumpWidget(Stack(
803
      textDirection: TextDirection.ltr,
804
      children: <Widget>[
805 806 807
        Container(key: key),
        Container(key: const ValueKey<int>(0)),
        Container(key: const ValueKey<int>(1), child: Container(key: key)),
808 809 810 811 812 813
      ],
    ));
    expect(tester.takeException(), isFlutterError);
  });

  testWidgets('GlobalKey duplication 16 - moving during build - after', (WidgetTester tester) async {
814 815
    final Key key = GlobalKey(debugLabel: 'problematic');
    await tester.pumpWidget(Stack(
816
      textDirection: TextDirection.ltr,
817
      children: <Widget>[
818 819 820
        Container(key: const ValueKey<int>(0)),
        Container(key: const ValueKey<int>(1)),
        Container(key: key),
821 822
      ],
    ));
823
    await tester.pumpWidget(Stack(
824
      textDirection: TextDirection.ltr,
825
      children: <Widget>[
826 827
        Container(key: const ValueKey<int>(0)),
        Container(key: const ValueKey<int>(1), child: Container(key: key)),
828 829 830 831 832
      ],
    ));
  });

  testWidgets('GlobalKey duplication 17 - duplicating during build - after', (WidgetTester tester) async {
833 834
    final Key key = GlobalKey(debugLabel: 'problematic');
    await tester.pumpWidget(Stack(
835
      textDirection: TextDirection.ltr,
836
      children: <Widget>[
837 838 839
        Container(key: const ValueKey<int>(0)),
        Container(key: const ValueKey<int>(1)),
        Container(key: key),
840 841 842
      ],
    ));
    int count = 0;
843
    final FlutterExceptionHandler? oldHandler = FlutterError.onError;
844 845 846 847
    FlutterError.onError = (FlutterErrorDetails details) {
      expect(details.exception, isFlutterError);
      count += 1;
    };
848
    await tester.pumpWidget(Stack(
849
      textDirection: TextDirection.ltr,
850
      children: <Widget>[
851 852 853
        Container(key: const ValueKey<int>(0)),
        Container(key: const ValueKey<int>(1), child: Container(key: key)),
        Container(key: key),
854 855 856
      ],
    ));
    FlutterError.onError = oldHandler;
857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890
    expect(count, 1);
  });

  testWidgets('GlobalKey duplication 18 - subtree build duplicate key with same type', (WidgetTester tester) async {
    final Key key = GlobalKey(debugLabel: 'problematic');
    final Stack stack = Stack(
      textDirection: TextDirection.ltr,
      children: <Widget>[
        const SwapKeyWidget(childKey: ValueKey<int>(0)),
        Container(key: const ValueKey<int>(1)),
        Container(key: key),
      ],
    );
    await tester.pumpWidget(stack);
    final SwapKeyWidgetState state = tester.state(find.byType(SwapKeyWidget));
    state.swapKey(key);
    await tester.pump();
    final dynamic exception = tester.takeException();
    expect(exception, isFlutterError);
    expect(
      exception.toString(),
      equalsIgnoringHashCodes(
        'Duplicate GlobalKey detected in widget tree.\n'
        'The following GlobalKey was specified multiple times in the widget tree. This will lead '
        'to parts of the widget tree being truncated unexpectedly, because the second time a key is seen, the '
        'previous instance is moved to the new location. The key was:\n'
        '- [GlobalKey#00000 problematic]\n'
        'This was determined by noticing that after the widget with the above global key was '
        'moved out of its previous parent, that previous parent never updated during this frame, meaning that '
        'it either did not update at all or updated before the widget was moved, in either case implying that '
        'it still thinks that it should have a child with that global key.\n'
        'The specific parent that did not update after having one or more children forcibly '
        'removed due to GlobalKey reparenting is:\n'
        '- Stack(alignment: AlignmentDirectional.topStart, textDirection: ltr, fit: loose, '
891
        'renderObject: RenderStack#00000)\n'
892
        'A GlobalKey can only be specified on one widget at a time in the widget tree.',
893 894 895 896 897 898 899 900 901 902 903
      ),
    );
  });

  testWidgets('GlobalKey duplication 19 - subtree build duplicate key with different types', (WidgetTester tester) async {
    final Key key = GlobalKey(debugLabel: 'problematic');
    final Stack stack = Stack(
      textDirection: TextDirection.ltr,
      children: <Widget>[
        const SwapKeyWidget(childKey: ValueKey<int>(0)),
        Container(key: const ValueKey<int>(1)),
904
        Container(color: Colors.green, child: SizedBox(key: key)),
905 906 907 908 909 910 911 912 913 914 915 916 917 918 919
      ],
    );
    await tester.pumpWidget(stack);
    final SwapKeyWidgetState state = tester.state(find.byType(SwapKeyWidget));
    state.swapKey(key);
    await tester.pump();
    final dynamic exception = tester.takeException();
    expect(exception, isFlutterError);
    expect(
      exception.toString(),
      equalsIgnoringHashCodes(
        'Multiple widgets used the same GlobalKey.\n'
        'The key [GlobalKey#95367 problematic] was used by 2 widgets:\n'
        '  SizedBox-[GlobalKey#00000 problematic]\n'
        '  Container-[GlobalKey#00000 problematic]\n'
920
        'A GlobalKey can only be specified on one widget at a time in the widget tree.',
921 922 923 924 925 926 927
      ),
    );
  });

  testWidgets('GlobalKey duplication 20 - real duplication with early rebuild in layoutbuilder will throw', (WidgetTester tester) async {
    const Key key1 = GlobalObjectKey('Text1');
    const Key key2 = GlobalObjectKey('Text2');
928 929 930
    Key? rebuiltKeyOfSecondChildBeforeLayout;
    Key? rebuiltKeyOfFirstChildAfterLayout;
    Key? rebuiltKeyOfSecondChildAfterLayout;
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
    await tester.pumpWidget(
      LayoutBuilder(
        builder: (BuildContext context, BoxConstraints constraints) {
          return Column(
            children: <Widget>[
              const _Stateful(
                child: Text(
                  'Text1',
                  textDirection: TextDirection.ltr,
                  key: key1,
                ),
              ),
              _Stateful(
                child: const Text(
                  'Text2',
                  textDirection: TextDirection.ltr,
                  key: key2,
                ),
                onElementRebuild: (StatefulElement element) {
                  // We don't want noise to override the result;
                  expect(rebuiltKeyOfSecondChildBeforeLayout, isNull);
                  final _Stateful statefulWidget = element.widget as _Stateful;
                  rebuiltKeyOfSecondChildBeforeLayout = statefulWidget.child.key;
                },
              ),
            ],
          );
        },
959
      ),
960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005
    );
    // Result will be written during first build and need to clear it to remove
    // noise.
    rebuiltKeyOfSecondChildBeforeLayout = null;

    final _StatefulState state = tester.firstState(find.byType(_Stateful).at(1));
    state.rebuild();

    await tester.pumpWidget(
      LayoutBuilder(
        builder: (BuildContext context, BoxConstraints constraints) {
          return Column(
            children: <Widget>[
              _Stateful(
                child: const Text(
                  'Text2',
                  textDirection: TextDirection.ltr,
                  key: key2,
                ),
                onElementRebuild: (StatefulElement element) {
                  // Verifies the early rebuild happens before layout.
                  expect(rebuiltKeyOfSecondChildBeforeLayout, key2);
                  // We don't want noise to override the result;
                  expect(rebuiltKeyOfFirstChildAfterLayout, isNull);
                  final _Stateful statefulWidget = element.widget as _Stateful;
                  rebuiltKeyOfFirstChildAfterLayout = statefulWidget.child.key;
                },
              ),
              _Stateful(
                child: const Text(
                  'Text1',
                  textDirection: TextDirection.ltr,
                  key: key2,
                ),
                onElementRebuild: (StatefulElement element) {
                  // Verifies the early rebuild happens before layout.
                  expect(rebuiltKeyOfSecondChildBeforeLayout, key2);
                  // We don't want noise to override the result;
                  expect(rebuiltKeyOfSecondChildAfterLayout, isNull);
                  final _Stateful statefulWidget = element.widget as _Stateful;
                  rebuiltKeyOfSecondChildAfterLayout = statefulWidget.child.key;
                },
              ),
            ],
          );
        },
1006
      ),
1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020
    );
    expect(rebuiltKeyOfSecondChildBeforeLayout, key2);
    expect(rebuiltKeyOfFirstChildAfterLayout, key2);
    expect(rebuiltKeyOfSecondChildAfterLayout, key2);
    final dynamic exception = tester.takeException();
    expect(exception, isFlutterError);
    expect(
      exception.toString(),
      equalsIgnoringHashCodes(
        'Multiple widgets used the same GlobalKey.\n'
        'The key [GlobalObjectKey String#00000] was used by multiple widgets. The '
        'parents of those widgets were:\n'
        '- _Stateful(state: _StatefulState#00000)\n'
        '- _Stateful(state: _StatefulState#00000)\n'
1021
        'A GlobalKey can only be specified on one widget at a time in the widget tree.',
1022 1023
      ),
    );
1024 1025
  });

1026
  testWidgets('GlobalKey - detach and re-attach child to different parents', (WidgetTester tester) async {
1027 1028 1029
    await tester.pumpWidget(Directionality(
      textDirection: TextDirection.ltr,
      child: Center(
1030
        child: SizedBox(
1031 1032 1033 1034 1035 1036 1037 1038
          height: 100,
          child: CustomScrollView(
            controller: ScrollController(),
            slivers: <Widget>[
              SliverList(
                delegate: SliverChildListDelegate(<Widget>[
                  Text('child', key: GlobalKey()),
                ]),
1039
              ),
1040 1041 1042 1043 1044 1045
            ],
          ),
        ),
      ),
    ));
    final SliverMultiBoxAdaptorElement element = tester.element(find.byType(SliverList));
1046
    late Element childElement;
1047 1048 1049 1050 1051
    // Removing and recreating child with same Global Key should not trigger
    // duplicate key error.
    element.visitChildren((Element e) {
      childElement = e;
    });
1052
    element.removeChild(childElement.renderObject! as RenderBox);
1053 1054 1055 1056
    element.createChild(0, after: null);
    element.visitChildren((Element e) {
      childElement = e;
    });
1057
    element.removeChild(childElement.renderObject! as RenderBox);
1058 1059 1060
    element.createChild(0, after: null);
  });

1061 1062 1063 1064
  testWidgets('GlobalKey - re-attach child to new parents, and the old parent is deactivated(unmounted)', (WidgetTester tester) async {
    // This is a regression test for https://github.com/flutter/flutter/issues/62055
    const Key key1 = GlobalObjectKey('key1');
    const Key key2 = GlobalObjectKey('key2');
1065
    late StateSetter setState;
1066
    int tabBarViewCnt = 2;
1067
    TabController tabController = TabController(length: tabBarViewCnt, vsync: const TestVSync());
1068 1069 1070 1071 1072 1073 1074 1075 1076

    await tester.pumpWidget(Directionality(
      textDirection: TextDirection.ltr,
      child: StatefulBuilder(
        builder: (BuildContext context, StateSetter setter) {
          setState = setter;
          return TabBarView(
            controller: tabController,
            children: <Widget>[
1077 1078
              if (tabBarViewCnt > 0) const Text('key1', key: key1),
              if (tabBarViewCnt > 1) const Text('key2', key: key2),
1079 1080 1081 1082 1083 1084 1085 1086 1087
            ],
          );
        },
      ),
    ));

    expect(tabController.index, 0);

    // switch tabs 0 -> 1
1088
    setState(() {
1089 1090 1091 1092 1093 1094 1095 1096
      tabController.index = 1;
    });

    await tester.pump(const Duration(seconds: 1)); // finish the animation

    expect(tabController.index, 1);

    // rebuild TabBarView that only have the 1st page with GlobalKey 'key1'
1097
    setState(() {
1098
      tabBarViewCnt = 1;
1099
      tabController = TabController(length: tabBarViewCnt, vsync: const TestVSync());
1100 1101 1102 1103 1104 1105 1106
    });

    await tester.pump(const Duration(seconds: 1)); // finish the animation

    expect(tabController.index, 0);
  });

1107
  testWidgets('Defunct setState throws exception', (WidgetTester tester) async {
1108
    late StateSetter setState;
1109

1110
    await tester.pumpWidget(StatefulBuilder(
1111 1112
      builder: (BuildContext context, StateSetter setter) {
        setState = setter;
1113
        return Container();
1114 1115 1116 1117 1118 1119
      },
    ));

    // Control check that setState doesn't throw an exception.
    setState(() { });

1120
    await tester.pumpWidget(Container());
1121 1122 1123 1124 1125

    expect(() { setState(() { }); }, throwsFlutterError);
  });

  testWidgets('State toString', (WidgetTester tester) async {
1126
    final TestState state = TestState();
1127
    expect(state.toString(), contains('no widget'));
1128 1129 1130 1131 1132 1133 1134 1135
  });

  testWidgets('debugPrintGlobalKeyedWidgetLifecycle control test', (WidgetTester tester) async {
    expect(debugPrintGlobalKeyedWidgetLifecycle, isFalse);

    final DebugPrintCallback oldCallback = debugPrint;
    debugPrintGlobalKeyedWidgetLifecycle = true;

1136
    final List<String> log = <String>[];
1137 1138
    debugPrint = (String? message, { int? wrapWidth }) {
      log.add(message!);
1139 1140
    };

1141 1142
    final GlobalKey key = GlobalKey();
    await tester.pumpWidget(Container(key: key));
1143
    expect(log, isEmpty);
1144
    await tester.pumpWidget(const Placeholder());
1145 1146 1147 1148 1149 1150 1151
    debugPrint = oldCallback;
    debugPrintGlobalKeyedWidgetLifecycle = false;

    expect(log.length, equals(2));
    expect(log[0], matches('Deactivated'));
    expect(log[1], matches('Discarding .+ from inactive elements list.'));
  });
1152 1153 1154

  testWidgets('MultiChildRenderObjectElement.children', (WidgetTester tester) async {
    GlobalKey key0, key1, key2;
1155 1156
    await tester.pumpWidget(Column(
      key: key0 = GlobalKey(),
1157
      children: <Widget>[
1158 1159
        Container(),
        Container(key: key1 = GlobalKey()),
1160
        Container(),
1161 1162
        Container(key: key2 = GlobalKey()),
        Container(),
1163 1164
      ],
    ));
1165
    final MultiChildRenderObjectElement element = key0.currentContext! as MultiChildRenderObjectElement;
1166
    expect(
1167
      element.children.map((Element element) => element.widget.key),
1168
      <Key?>[null, key1, null, key2, null],
1169 1170
    );
  });
1171

1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191
  testWidgets('Can not attach a non-RenderObjectElement to the MultiChildRenderObjectElement - mount', (WidgetTester tester) async {
    await tester.pumpWidget(
      Column(
        children: <Widget>[
          Container(),
          const _EmptyWidget(),
        ],
      ),
    );

    final dynamic exception = tester.takeException();
    expect(exception, isFlutterError);
    expect(
      exception.toString(),
      equalsIgnoringHashCodes(
        'The children of `MultiChildRenderObjectElement` must each has an associated render object.\n'
        'This typically means that the `_EmptyWidget` or its children\n'
        'are not a subtype of `RenderObjectWidget`.\n'
        'The following element does not have an associated render object:\n'
        '  _EmptyWidget\n'
1192
        'debugCreator: _EmptyWidget ← Column ← [root]',
1193 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
      ),
    );
  });

  testWidgets('Can not attach a non-RenderObjectElement to the MultiChildRenderObjectElement - update', (WidgetTester tester) async {
    await tester.pumpWidget(
      Column(
        children: <Widget>[
          Container(),
        ],
      ),
    );

    await tester.pumpWidget(
      Column(
        children: <Widget>[
          Container(),
          const _EmptyWidget(),
        ],
      ),
    );

    final dynamic exception = tester.takeException();
    expect(exception, isFlutterError);
    expect(
      exception.toString(),
      equalsIgnoringHashCodes(
        'The children of `MultiChildRenderObjectElement` must each has an associated render object.\n'
        'This typically means that the `_EmptyWidget` or its children\n'
        'are not a subtype of `RenderObjectWidget`.\n'
        'The following element does not have an associated render object:\n'
        '  _EmptyWidget\n'
1225
        'debugCreator: _EmptyWidget ← Column ← [root]',
1226 1227 1228 1229
      ),
    );
  });

1230 1231
  testWidgets('Element diagnostics', (WidgetTester tester) async {
    GlobalKey key0;
1232 1233
    await tester.pumpWidget(Column(
      key: key0 = GlobalKey(),
1234
      children: <Widget>[
1235 1236
        Container(),
        Container(key: GlobalKey()),
1237
        Container(color: Colors.green, child: Container()),
1238 1239
        Container(key: GlobalKey()),
        Container(),
1240 1241
      ],
    ));
1242
    final MultiChildRenderObjectElement element = key0.currentContext! as MultiChildRenderObjectElement;
1243

1244 1245 1246 1247
    expect(element, hasAGoodToStringDeep);
    expect(
      element.toStringDeep(),
      equalsIgnoringHashCodes(
1248
        'Column-[GlobalKey#00000](direction: vertical, mainAxisAlignment: start, crossAxisAlignment: center, renderObject: RenderFlex#00000)\n'
1249 1250 1251 1252 1253 1254
        '├Container\n'
        '│└LimitedBox(maxWidth: 0.0, maxHeight: 0.0, renderObject: RenderLimitedBox#00000 relayoutBoundary=up1)\n'
        '│ └ConstrainedBox(BoxConstraints(biggest), renderObject: RenderConstrainedBox#00000 relayoutBoundary=up2)\n'
        '├Container-[GlobalKey#00000]\n'
        '│└LimitedBox(maxWidth: 0.0, maxHeight: 0.0, renderObject: RenderLimitedBox#00000 relayoutBoundary=up1)\n'
        '│ └ConstrainedBox(BoxConstraints(biggest), renderObject: RenderConstrainedBox#00000 relayoutBoundary=up2)\n'
1255 1256 1257 1258 1259
        '├Container(bg: MaterialColor(primary value: Color(0xff4caf50)))\n'
        '│└ColoredBox(color: MaterialColor(primary value: Color(0xff4caf50)), renderObject: _RenderColoredBox#00000 relayoutBoundary=up1)\n'
        '│ └Container\n'
        '│  └LimitedBox(maxWidth: 0.0, maxHeight: 0.0, renderObject: RenderLimitedBox#00000 relayoutBoundary=up2)\n'
        '│   └ConstrainedBox(BoxConstraints(biggest), renderObject: RenderConstrainedBox#00000 relayoutBoundary=up3)\n'
1260 1261 1262 1263 1264 1265
        '├Container-[GlobalKey#00000]\n'
        '│└LimitedBox(maxWidth: 0.0, maxHeight: 0.0, renderObject: RenderLimitedBox#00000 relayoutBoundary=up1)\n'
        '│ └ConstrainedBox(BoxConstraints(biggest), renderObject: RenderConstrainedBox#00000 relayoutBoundary=up2)\n'
        '└Container\n'
        ' └LimitedBox(maxWidth: 0.0, maxHeight: 0.0, renderObject: RenderLimitedBox#00000 relayoutBoundary=up1)\n'
        '  └ConstrainedBox(BoxConstraints(biggest), renderObject: RenderConstrainedBox#00000 relayoutBoundary=up2)\n',
1266 1267
      ),
    );
1268
  });
1269

1270
  testWidgets('scheduleBuild while debugBuildingDirtyElements is true', (WidgetTester tester) async {
1271
    // ignore here is required for testing purpose because changing the flag properly is hard
1272 1273
    // ignore: invalid_use_of_protected_member
    tester.binding.debugBuildingDirtyElements = true;
1274
    late FlutterError error;
1275
    try {
1276
      tester.binding.buildOwner!.scheduleBuildFor(
1277 1278
        DirtyElementWithCustomBuildOwner(tester.binding.buildOwner!, Container()),
      );
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
    } on FlutterError catch (e) {
      error = e;
    } finally {
      expect(error.diagnostics.length, 3);
      expect(error.diagnostics.last.level, DiagnosticLevel.hint);
      expect(
        error.diagnostics.last.toStringDeep(),
        equalsIgnoringHashCodes(
          'This might be because setState() was called from a layout or\n'
          'paint callback. If a change is needed to the widget tree, it\n'
          'should be applied as the tree is being built. Scheduling a change\n'
          'for the subsequent frame instead results in an interface that\n'
          'lags behind by one frame. If this was done to make your build\n'
          'dependent on a size measured at layout time, consider using a\n'
          'LayoutBuilder, CustomSingleChildLayout, or\n'
          'CustomMultiChildLayout. If, on the other hand, the one frame\n'
          'delay is the desired effect, for example because this is an\n'
          'animation, consider scheduling the frame in a post-frame callback\n'
          'using SchedulerBinding.addPostFrameCallback or using an\n'
          'AnimationController to trigger the animation.\n',
        ),
      );
      expect(
        error.toStringDeep(),
        'FlutterError\n'
        '   Build scheduled during frame.\n'
        '   While the widget tree was being built, laid out, and painted, a\n'
        '   new frame was scheduled to rebuild the widget tree.\n'
        '   This might be because setState() was called from a layout or\n'
        '   paint callback. If a change is needed to the widget tree, it\n'
        '   should be applied as the tree is being built. Scheduling a change\n'
        '   for the subsequent frame instead results in an interface that\n'
        '   lags behind by one frame. If this was done to make your build\n'
        '   dependent on a size measured at layout time, consider using a\n'
        '   LayoutBuilder, CustomSingleChildLayout, or\n'
        '   CustomMultiChildLayout. If, on the other hand, the one frame\n'
        '   delay is the desired effect, for example because this is an\n'
        '   animation, consider scheduling the frame in a post-frame callback\n'
        '   using SchedulerBinding.addPostFrameCallback or using an\n'
        '   AnimationController to trigger the animation.\n',
      );
    }
  });
1322 1323 1324 1325 1326 1327

  testWidgets('didUpdateDependencies is not called on a State that never rebuilds', (WidgetTester tester) async {
    final GlobalKey<DependentState> key = GlobalKey<DependentState>();

    /// Initial build - should call didChangeDependencies, not deactivate
    await tester.pumpWidget(Inherited(1, child: DependentStatefulWidget(key: key)));
1328
    final DependentState state = key.currentState!;
1329 1330 1331 1332 1333 1334 1335 1336 1337 1338
    expect(key.currentState, isNotNull);
    expect(state.didChangeDependenciesCount, 1);
    expect(state.deactivatedCount, 0);

    /// Rebuild with updated value - should call didChangeDependencies
    await tester.pumpWidget(Inherited(2, child: DependentStatefulWidget(key: key)));
    expect(key.currentState, isNotNull);
    expect(state.didChangeDependenciesCount, 2);
    expect(state.deactivatedCount, 0);

1339
    // reparent it - should call deactivate and didChangeDependencies
1340 1341 1342 1343 1344
    await tester.pumpWidget(Inherited(3, child: SizedBox(child: DependentStatefulWidget(key: key))));
    expect(key.currentState, isNotNull);
    expect(state.didChangeDependenciesCount, 3);
    expect(state.deactivatedCount, 1);

1345
    // Remove it - should call deactivate, but not didChangeDependencies
1346 1347 1348 1349 1350
    await tester.pumpWidget(const Inherited(4, child: SizedBox()));
    expect(key.currentState, isNull);
    expect(state.didChangeDependenciesCount, 3);
    expect(state.deactivatedCount, 2);
  });
Dan Field's avatar
Dan Field committed
1351 1352

  testWidgets('StatefulElement subclass can decorate State.build', (WidgetTester tester) async {
1353 1354
    late bool isDidChangeDependenciesDecorated;
    late bool isBuildDecorated;
Dan Field's avatar
Dan Field committed
1355 1356 1357 1358 1359 1360 1361

    final Widget child = Decorate(
      didChangeDependencies: (bool value) {
        isDidChangeDependenciesDecorated = value;
      },
      build: (bool value) {
        isBuildDecorated = value;
1362
      },
Dan Field's avatar
Dan Field committed
1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374
    );

    await tester.pumpWidget(Inherited(0, child: child));

    expect(isBuildDecorated, isTrue);
    expect(isDidChangeDependenciesDecorated, isFalse);

    await tester.pumpWidget(Inherited(1, child: child));

    expect(isBuildDecorated, isTrue);
    expect(isDidChangeDependenciesDecorated, isFalse);
  });
1375 1376
  group('BuildContext.debugDoingbuild', () {
    testWidgets('StatelessWidget', (WidgetTester tester) async {
1377
      late bool debugDoingBuildOnBuild;
1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391
      await tester.pumpWidget(
        StatelessWidgetSpy(
          onBuild: (BuildContext context) {
            debugDoingBuildOnBuild = context.debugDoingBuild;
          },
        ),
      );

      final Element context = tester.element(find.byType(StatelessWidgetSpy));

      expect(context.debugDoingBuild, isFalse);
      expect(debugDoingBuildOnBuild, isTrue);
    });
    testWidgets('StatefulWidget', (WidgetTester tester) async {
1392 1393 1394 1395 1396 1397
      late bool debugDoingBuildOnBuild;
      late bool debugDoingBuildOnInitState;
      late bool debugDoingBuildOnDidChangeDependencies;
      late bool debugDoingBuildOnDidUpdateWidget;
      bool? debugDoingBuildOnDispose;
      bool? debugDoingBuildOnDeactivate;
1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 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 1436

      await tester.pumpWidget(
        Inherited(
          0,
          child: StatefulWidgetSpy(
            onInitState: (BuildContext context) {
              debugDoingBuildOnInitState = context.debugDoingBuild;
            },
            onDidChangeDependencies: (BuildContext context) {
              context.dependOnInheritedWidgetOfExactType<Inherited>();
              debugDoingBuildOnDidChangeDependencies = context.debugDoingBuild;
            },
            onBuild: (BuildContext context) {
              debugDoingBuildOnBuild = context.debugDoingBuild;
            },
          ),
        ),
      );

      final Element context = tester.element(find.byType(StatefulWidgetSpy));

      expect(context.debugDoingBuild, isFalse);
      expect(debugDoingBuildOnBuild, isTrue);
      expect(debugDoingBuildOnInitState, isFalse);
      expect(debugDoingBuildOnDidChangeDependencies, isFalse);

      await tester.pumpWidget(
        Inherited(
          1,
          child: StatefulWidgetSpy(
            onDidUpdateWidget: (BuildContext context) {
              debugDoingBuildOnDidUpdateWidget = context.debugDoingBuild;
            },
            onDidChangeDependencies: (BuildContext context) {
              debugDoingBuildOnDidChangeDependencies = context.debugDoingBuild;
            },
            onBuild: (BuildContext context) {
              debugDoingBuildOnBuild = context.debugDoingBuild;
            },
1437
            onDispose: (BuildContext context) {
1438 1439
              debugDoingBuildOnDispose = context.debugDoingBuild;
            },
1440
            onDeactivate: (BuildContext context) {
1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460
              debugDoingBuildOnDeactivate = context.debugDoingBuild;
            },
          ),
        ),
      );

      expect(context.debugDoingBuild, isFalse);
      expect(debugDoingBuildOnBuild, isTrue);
      expect(debugDoingBuildOnDidUpdateWidget, isFalse);
      expect(debugDoingBuildOnDidChangeDependencies, isFalse);
      expect(debugDoingBuildOnDeactivate, isNull);
      expect(debugDoingBuildOnDispose, isNull);

      await tester.pumpWidget(Container());

      expect(context.debugDoingBuild, isFalse);
      expect(debugDoingBuildOnDispose, isFalse);
      expect(debugDoingBuildOnDeactivate, isFalse);
    });
    testWidgets('RenderObjectWidget', (WidgetTester tester) async {
1461 1462 1463
      late bool debugDoingBuildOnCreateRenderObject;
      bool? debugDoingBuildOnUpdateRenderObject;
      bool? debugDoingBuildOnDidUnmountRenderObject;
1464 1465
      final ValueNotifier<int> notifier = ValueNotifier<int>(0);

1466
      late BuildContext spyContext;
1467 1468 1469 1470

      Widget build() {
        return ValueListenableBuilder<int>(
          valueListenable: notifier,
1471 1472
          builder: (BuildContext context, int? value, Widget? child) {
            return Inherited(value, child: child!);
1473 1474
          },
          child: RenderObjectWidgetSpy(
1475
            onCreateRenderObject: (BuildContext context) {
1476 1477 1478 1479 1480 1481 1482
              spyContext = context;
              context.dependOnInheritedWidgetOfExactType<Inherited>();
              debugDoingBuildOnCreateRenderObject = context.debugDoingBuild;
            },
            onUpdateRenderObject: (BuildContext context) {
              debugDoingBuildOnUpdateRenderObject = context.debugDoingBuild;
            },
1483
            onDidUnmountRenderObject: () {
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 1513 1514 1515 1516 1517 1518
              debugDoingBuildOnDidUnmountRenderObject = spyContext.debugDoingBuild;
            },
          ),
        );
      }

      await tester.pumpWidget(build());

      spyContext = tester.element(find.byType(RenderObjectWidgetSpy));

      expect(spyContext.debugDoingBuild, isFalse);
      expect(debugDoingBuildOnCreateRenderObject, isTrue);
      expect(debugDoingBuildOnUpdateRenderObject, isNull);
      expect(debugDoingBuildOnDidUnmountRenderObject, isNull);

      await tester.pumpWidget(build());

      expect(spyContext.debugDoingBuild, isFalse);
      expect(debugDoingBuildOnUpdateRenderObject, isTrue);
      expect(debugDoingBuildOnDidUnmountRenderObject, isNull);

      notifier.value++;
      debugDoingBuildOnUpdateRenderObject = false;
      await tester.pump();

      expect(spyContext.debugDoingBuild, isFalse);
      expect(debugDoingBuildOnUpdateRenderObject, isTrue);
      expect(debugDoingBuildOnDidUnmountRenderObject, isNull);

      await tester.pumpWidget(Container());

      expect(spyContext.debugDoingBuild, isFalse);
      expect(debugDoingBuildOnDidUnmountRenderObject, isFalse);
    });
  });
1519 1520 1521

  testWidgets('A widget whose element has an invalid visitChildren implementation triggers a useful error message', (WidgetTester tester) async {
    final GlobalKey key = GlobalKey();
1522
    await tester.pumpWidget(_WidgetWithNoVisitChildren(_StatefulLeaf(key: key)));
1523
    (key.currentState! as _StatefulLeafState).markNeedsBuild();
1524 1525 1526
    await tester.pumpWidget(Container());
    final dynamic exception = tester.takeException();
    expect(
1527
      // ignore: avoid_dynamic_calls
1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540
      exception.message,
      equalsIgnoringHashCodes(
        'Tried to build dirty widget in the wrong build scope.\n'
        'A widget which was marked as dirty and is still active was scheduled to be built, '
        'but the current build scope unexpectedly does not contain that widget.\n'
        'Sometimes this is detected when an element is removed from the widget tree, but '
        'the element somehow did not get marked as inactive. In that case, it might be '
        'caused by an ancestor element failing to implement visitChildren correctly, thus '
        'preventing some or all of its descendants from being correctly deactivated.\n'
        'The root of the build scope was:\n'
        '  [root]\n'
        'The offending element (which does not appear to be a descendant of the root of '
        'the build scope) was:\n'
1541 1542
        '  _StatefulLeaf-[GlobalKey#00000]',
      ),
1543 1544
    );
  });
1545 1546

  testWidgets('Can create BuildOwner that does not interfere with pointer router or raw key event handler', (WidgetTester tester) async {
1547
    final int pointerRouterCount = GestureBinding.instance.pointerRouter.debugGlobalRouteCount;
1548 1549
    final RawKeyEventHandler? rawKeyEventHandler = RawKeyboard.instance.keyEventHandler;
    expect(rawKeyEventHandler, isNotNull);
1550
    BuildOwner(focusManager: FocusManager());
1551
    expect(GestureBinding.instance.pointerRouter.debugGlobalRouteCount, pointerRouterCount);
1552 1553
    expect(RawKeyboard.instance.keyEventHandler, same(rawKeyEventHandler));
  });
1554 1555 1556 1557 1558 1559

  testWidgets('Can access debugFillProperties without _LateInitializationError', (WidgetTester tester) async {
    final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder();
    TestRenderObjectElement().debugFillProperties(builder);
    expect(builder.properties.any((DiagnosticsNode property) => property.name == 'renderObject' && property.value == null), isTrue);
  });
1560

1561 1562 1563 1564 1565 1566 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
  testWidgets('debugFillProperties sorts dependencies in alphabetical order', (WidgetTester tester) async {
    final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder();
    final TestRenderObjectElement element = TestRenderObjectElement();

    final _TestInheritedElement focusTraversalOrder =
    _TestInheritedElement(const FocusTraversalOrder(
      order: LexicalFocusOrder(''),
      child: Placeholder(),
    ));
    final _TestInheritedElement directionality =
        _TestInheritedElement(const Directionality(
      textDirection: TextDirection.ltr,
      child: Placeholder(),
    ));
    final _TestInheritedElement buttonBarTheme =
        _TestInheritedElement(const ButtonBarTheme(
        data: ButtonBarThemeData(
          alignment: MainAxisAlignment.center,
        ),
      child: Placeholder(),
    ));

    // Dependencies are added out of alphabetical order.
    element
      ..dependOnInheritedElement(focusTraversalOrder)
      ..dependOnInheritedElement(directionality)
      ..dependOnInheritedElement(buttonBarTheme);

    // Dependencies will be sorted by [debugFillProperties].
    element.debugFillProperties(builder);

    expect(
      builder.properties.any((DiagnosticsNode property) => property.name == 'dependencies' && property.value != null),
      isTrue,
    );
    final DiagnosticsProperty<List<DiagnosticsNode>> dependenciesProperty =
        builder.properties.firstWhere((DiagnosticsNode property) => property.name == 'dependencies') as DiagnosticsProperty<List<DiagnosticsNode>>;
    expect(dependenciesProperty, isNotNull);

    final List<DiagnosticsNode> dependencies = dependenciesProperty.value!;
    expect(dependencies.length, equals(3));
    expect(dependencies.toString(), '[ButtonBarTheme, Directionality, FocusTraversalOrder]');
  });

1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617
  testWidgets('BuildOwner.globalKeyCount keeps track of in-use global keys', (WidgetTester tester) async {
    final int initialCount = tester.binding.buildOwner!.globalKeyCount;
    final GlobalKey key1 = GlobalKey();
    final GlobalKey key2 = GlobalKey();
    await tester.pumpWidget(Container(key: key1));
    expect(tester.binding.buildOwner!.globalKeyCount, initialCount + 1);
    await tester.pumpWidget(Container(key: key1, child: Container()));
    expect(tester.binding.buildOwner!.globalKeyCount, initialCount + 1);
    await tester.pumpWidget(Container(key: key1, child: Container(key: key2)));
    expect(tester.binding.buildOwner!.globalKeyCount, initialCount + 2);
    await tester.pumpWidget(Container());
    expect(tester.binding.buildOwner!.globalKeyCount, initialCount + 0);
  });
1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632

  testWidgets('Widget and State properties are nulled out when unmounted', (WidgetTester tester) async {
    await tester.pumpWidget(const _StatefulLeaf());
    final StatefulElement element = tester.element<StatefulElement>(find.byType(_StatefulLeaf));
    expect(element.state, isA<State<_StatefulLeaf>>());
    expect(element.widget, isA<_StatefulLeaf>());
    // Replace the widget tree to unmount the element.
    await tester.pumpWidget(Container());
    // Accessing state/widget now throws a CastError because they have been
    // nulled out to reduce severity of memory leaks when an Element (e.g. in
    // the form of a BuildContext) is retained past its useful life. See also
    // https://github.com/flutter/flutter/issues/79605 for examples why this may
    // occur.
    expect(() => element.state, throwsA(isA<TypeError>()));
    expect(() => element.widget, throwsA(isA<TypeError>()));
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('LayerLink can be swapped between parent and child container layers', (WidgetTester tester) async {
    // Regression test for https://github.com/flutter/flutter/issues/96959.
    final LayerLink link = LayerLink();
    await tester.pumpWidget(_TestLeaderLayerWidget(
        link: link,
        child: const _TestLeaderLayerWidget(
          child: Placeholder(),
        )
    ));
    expect(tester.takeException(), isNull);

    // Swaps the layer link.
    await tester.pumpWidget(_TestLeaderLayerWidget(
        child: _TestLeaderLayerWidget(
          link: link,
          child: const Placeholder(),
        ),
    ));
    expect(tester.takeException(), isNull);

  });

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
  testWidgets('Deactivate and activate are called correctly', (WidgetTester tester) async {
    final List<String> states = <String>[];
    Widget build([Key? key]) {
      return StatefulWidgetSpy(
        key: key,
        onInitState: (BuildContext context) { states.add('initState'); },
        onDidUpdateWidget: (BuildContext context) { states.add('didUpdateWidget'); },
        onDeactivate: (BuildContext context) { states.add('deactivate'); },
        onActivate: (BuildContext context) { states.add('activate'); },
        onBuild: (BuildContext context) { states.add('build'); },
        onDispose: (BuildContext context) { states.add('dispose'); },
      );
    }
    Future<void> pumpWidget(Widget widget) {
      states.clear();
      return tester.pumpWidget(widget);
    }

    await pumpWidget(build());
    expect(states, <String>['initState', 'build']);
    await pumpWidget(Container(child: build()));
    expect(states, <String>['deactivate', 'initState', 'build', 'dispose']);
    await pumpWidget(Container());
    expect(states, <String>['deactivate', 'dispose']);

    final GlobalKey key = GlobalKey();
    await pumpWidget(build(key));
    expect(states, <String>['initState', 'build']);
    await pumpWidget(Container(child: build(key)));
    expect(states, <String>['deactivate', 'activate', 'didUpdateWidget', 'build']);
    await pumpWidget(Container());
    expect(states, <String>['deactivate', 'dispose']);
  });
1690

1691
  testWidgets('RenderObjectElement.unmount disposes of its renderObject', (WidgetTester tester) async {
1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702
    await tester.pumpWidget(const Placeholder());
    final RenderObjectElement element = tester.allElements.whereType<RenderObjectElement>().first;
    final RenderObject renderObject = element.renderObject;
    expect(renderObject.debugDisposed, false);

    await tester.pumpWidget(Container());

    expect(() => element.renderObject, throwsAssertionError);
    expect(renderObject.debugDisposed, true);
  });

1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725
  testWidgets('Getting the render object of an unmounted element throws', (WidgetTester tester) async {
    await tester.pumpWidget(const _StatefulLeaf());
    final StatefulElement element = tester.element<StatefulElement>(find.byType(_StatefulLeaf));
    expect(element.state, isA<State<_StatefulLeaf>>());
    expect(element.widget, isA<_StatefulLeaf>());
    // Replace the widget tree to unmount the element.
    await tester.pumpWidget(Container());

  expect(
    () => element.findRenderObject(),
    throwsA(isA<FlutterError>().having(
      (FlutterError error) => error.message,
      'message',
      equalsIgnoringHashCodes('''
Cannot get renderObject of inactive element.
In order for an element to have a valid renderObject, it must be active, which means it is part of the tree.
Instead, this element is in the _ElementLifecycle.defunct state.
If you called this method from a State object, consider guarding it with State.mounted.
The findRenderObject() method was called for the following element:
  StatefulElement#00000(DEFUNCT)'''),
      )),
    );
  });
1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740

  testWidgets('Elements use the identity hashCode', (WidgetTester tester) async {
    final StatefulElement statefulElement = StatefulElement(const _StatefulLeaf());
    expect(statefulElement.hashCode, identityHashCode(statefulElement));

    final StatelessElement statelessElement = StatelessElement(const Placeholder());

    expect(statelessElement.hashCode, identityHashCode(statelessElement));

    final InheritedElement inheritedElement = InheritedElement(
      const Directionality(textDirection: TextDirection.ltr, child: Placeholder()),
    );

    expect(inheritedElement.hashCode, identityHashCode(inheritedElement));
  });
1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764

  testWidgets('doesDependOnInheritedElement', (WidgetTester tester) async {
    final _TestInheritedElement ancestor =
        _TestInheritedElement(const Directionality(
      textDirection: TextDirection.ltr,
      child: Placeholder(),
    ));
    final _TestInheritedElement child =
        _TestInheritedElement(const Directionality(
      textDirection: TextDirection.ltr,
      child: Placeholder(),
    ));
    expect(child.doesDependOnInheritedElement(ancestor), isFalse);
    child.dependOnInheritedElement(ancestor);
    expect(child.doesDependOnInheritedElement(ancestor), isTrue);
  });
}

class _TestInheritedElement extends InheritedElement {
  _TestInheritedElement(super.widget);
  @override
  bool doesDependOnInheritedElement(InheritedElement element) {
    return super.doesDependOnInheritedElement(element);
  }
1765 1766
}

1767
class _WidgetWithNoVisitChildren extends StatelessWidget {
1768
  const _WidgetWithNoVisitChildren(this.child);
1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779

  final Widget child;

  @override
  Widget build(BuildContext context) => child;

  @override
  _WidgetWithNoVisitChildrenElement createElement() => _WidgetWithNoVisitChildrenElement(this);
}

class _WidgetWithNoVisitChildrenElement extends StatelessElement {
1780
  _WidgetWithNoVisitChildrenElement(_WidgetWithNoVisitChildren super.widget);
1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791

  @override
  void visitChildren(ElementVisitor visitor) {
    // This implementation is intentionally buggy, to test that an error message is
    // shown when this situation occurs.
    // The superclass has the correct implementation (calling `visitor(_child)`), so
    // we don't call it here.
  }
}

class _StatefulLeaf extends StatefulWidget {
1792
  const _StatefulLeaf({ super.key });
1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806

  @override
  State<_StatefulLeaf> createState() => _StatefulLeafState();
}

class _StatefulLeafState extends State<_StatefulLeaf> {
  void markNeedsBuild() {
    setState(() { });
  }

  @override
  Widget build(BuildContext context) {
    return const SizedBox.shrink();
  }
Dan Field's avatar
Dan Field committed
1807 1808 1809 1810
}

class Decorate extends StatefulWidget {
  const Decorate({
1811
    super.key,
1812
    required this.didChangeDependencies,
1813
    required this.build,
Dan Field's avatar
Dan Field committed
1814 1815
  }) :
    assert(didChangeDependencies != null),
1816
    assert(build != null);
Dan Field's avatar
Dan Field committed
1817 1818 1819 1820 1821

  final void Function(bool isInBuild) didChangeDependencies;
  final void Function(bool isInBuild) build;

  @override
1822
  State<Decorate> createState() => _DecorateState();
Dan Field's avatar
Dan Field committed
1823 1824 1825 1826 1827 1828

  @override
  DecorateElement createElement() => DecorateElement(this);
}

class DecorateElement extends StatefulElement {
1829
  DecorateElement(Decorate super.widget);
Dan Field's avatar
Dan Field committed
1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855

  bool isDecorated = false;

  @override
  Widget build() {
    try {
      isDecorated = true;
      return super.build();
    } finally {
      isDecorated = false;
    }
  }
}

class _DecorateState extends State<Decorate> {
  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    widget.didChangeDependencies.call((context as DecorateElement).isDecorated);
  }
  @override
  Widget build(covariant DecorateElement context) {
    context.dependOnInheritedWidgetOfExactType<Inherited>();
    widget.build.call(context.isDecorated);
    return Container();
  }
1856 1857
}

1858
class DirtyElementWithCustomBuildOwner extends Element {
1859 1860
  DirtyElementWithCustomBuildOwner(BuildOwner buildOwner, super.widget)
    : _owner = buildOwner;
1861 1862 1863 1864 1865 1866 1867 1868

  final BuildOwner _owner;

  @override
  BuildOwner get owner => _owner;

  @override
  bool get dirty => true;
1869 1870 1871

  @override
  bool get debugDoingBuild => throw UnimplementedError();
1872
}
1873 1874

class Inherited extends InheritedWidget {
1875
  const Inherited(this.value, {super.key, required super.child});
1876

1877
  final int? value;
1878 1879 1880 1881 1882 1883

  @override
  bool updateShouldNotify(Inherited oldWidget) => oldWidget.value != value;
}

class DependentStatefulWidget extends StatefulWidget {
1884
  const DependentStatefulWidget({super.key});
1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911

  @override
  State<StatefulWidget> createState() => DependentState();
}

class DependentState extends State<DependentStatefulWidget> {
  int didChangeDependenciesCount = 0;
  int deactivatedCount = 0;

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    didChangeDependenciesCount += 1;
  }

  @override
  Widget build(BuildContext context) {
    context.dependOnInheritedWidgetOfExactType<Inherited>();
    return const SizedBox();
  }

  @override
  void deactivate() {
    super.deactivate();
    deactivatedCount += 1;
  }
}
1912 1913

class SwapKeyWidget extends StatefulWidget {
1914
  const SwapKeyWidget({super.key, this.childKey});
1915

1916
  final Key? childKey;
1917 1918 1919 1920 1921
  @override
  SwapKeyWidgetState createState() => SwapKeyWidgetState();
}

class SwapKeyWidgetState extends State<SwapKeyWidget> {
1922
  Key? key;
1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942

  @override
  void initState() {
    super.initState();
    key = widget.childKey;
  }

  void swapKey(Key newKey) {
    setState(() {
      key = newKey;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(key: key);
  }
}

class _Stateful extends StatefulWidget {
1943
  const _Stateful({required this.child, this.onElementRebuild});
1944
  final Text child;
1945
  final ElementRebuildCallback? onElementRebuild;
1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962
  @override
  State<StatefulWidget> createState() => _StatefulState();

  @override
  StatefulElement createElement() => StatefulElementSpy(this);
}

class _StatefulState extends State<_Stateful> {
  void rebuild() => setState(() {});

  @override
  Widget build(BuildContext context) {
    return widget.child;
  }
}

class StatefulElementSpy extends StatefulElement {
1963
  StatefulElementSpy(super.widget);
1964 1965 1966 1967

  _Stateful get _statefulWidget => widget as _Stateful;

  @override
1968
  void rebuild({bool force = false}) {
1969
    _statefulWidget.onElementRebuild?.call(this);
1970
    super.rebuild(force: force);
1971 1972
  }
}
1973 1974 1975

class StatelessWidgetSpy extends StatelessWidget {
  const StatelessWidgetSpy({
1976
    super.key,
1977
    required this.onBuild,
1978
  })  : assert(onBuild != null);
1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990

  final void Function(BuildContext) onBuild;

  @override
  Widget build(BuildContext context) {
    onBuild(context);
    return Container();
  }
}

class StatefulWidgetSpy extends StatefulWidget {
  const StatefulWidgetSpy({
1991
    super.key,
1992 1993 1994 1995 1996
    this.onBuild,
    this.onInitState,
    this.onDidChangeDependencies,
    this.onDispose,
    this.onDeactivate,
1997
    this.onActivate,
1998
    this.onDidUpdateWidget,
1999
  });
2000

2001 2002 2003 2004 2005
  final void Function(BuildContext)? onBuild;
  final void Function(BuildContext)? onInitState;
  final void Function(BuildContext)? onDidChangeDependencies;
  final void Function(BuildContext)? onDispose;
  final void Function(BuildContext)? onDeactivate;
2006
  final void Function(BuildContext)? onActivate;
2007
  final void Function(BuildContext)? onDidUpdateWidget;
2008 2009

  @override
2010
  State<StatefulWidgetSpy> createState() => _StatefulWidgetSpyState();
2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023
}

class _StatefulWidgetSpyState extends State<StatefulWidgetSpy> {
  @override
  void initState() {
    super.initState();
    widget.onInitState?.call(context);
  }

  @override
  void deactivate() {
    super.deactivate();
    widget.onDeactivate?.call(context);
2024 2025 2026 2027 2028 2029
  }

  @override
  void activate() {
    super.activate();
    widget.onActivate?.call(context);
2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058
  }

  @override
  void dispose() {
    super.dispose();
    widget.onDispose?.call(context);
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    widget.onDidChangeDependencies?.call(context);
  }

  @override
  void didUpdateWidget(StatefulWidgetSpy oldWidget) {
    super.didUpdateWidget(oldWidget);
    widget.onDidUpdateWidget?.call(context);
  }

  @override
  Widget build(BuildContext context) {
    widget.onBuild?.call(context);
    return Container();
  }
}

class RenderObjectWidgetSpy extends LeafRenderObjectWidget {
  const RenderObjectWidgetSpy({
2059
    super.key,
2060
    this.onCreateRenderObject,
2061
    this.onUpdateRenderObject,
2062
    this.onDidUnmountRenderObject,
2063
  });
2064

2065 2066 2067
  final void Function(BuildContext)? onCreateRenderObject;
  final void Function(BuildContext)? onUpdateRenderObject;
  final void Function()? onDidUnmountRenderObject;
2068 2069 2070

  @override
  RenderObject createRenderObject(BuildContext context) {
2071
    onCreateRenderObject?.call(context);
2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082
    return FakeLeafRenderObject();
  }

  @override
  void updateRenderObject(BuildContext context, RenderObject renderObject) {
    onUpdateRenderObject?.call(context);
  }

  @override
  void didUnmountRenderObject(RenderObject renderObject) {
    super.didUnmountRenderObject(renderObject);
2083
    onDidUnmountRenderObject?.call();
2084 2085 2086 2087
  }
}

class FakeLeafRenderObject extends RenderBox {
2088 2089 2090 2091 2092
  @override
  Size computeDryLayout(BoxConstraints constraints) {
    return constraints.biggest;
  }

2093 2094 2095 2096 2097
  @override
  void performLayout() {
    size = constraints.biggest;
  }
}
2098 2099 2100 2101

class TestRenderObjectElement extends RenderObjectElement {
  TestRenderObjectElement() : super(Table());
}
2102 2103

class _EmptyWidget extends Widget {
2104
  const _EmptyWidget();
2105 2106 2107 2108 2109 2110

  @override
  Element createElement() => _EmptyElement(this);
}

class _EmptyElement extends Element {
2111
  _EmptyElement(_EmptyWidget super.widget);
2112 2113 2114 2115

  @override
  bool get debugDoingBuild => false;
}
2116 2117 2118 2119

class _TestLeaderLayerWidget extends SingleChildRenderObjectWidget {
  const _TestLeaderLayerWidget({
    this.link,
2120 2121
    super.child,
  });
2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164
  final LayerLink? link;

  @override
  _RenderTestLeaderLayerWidget createRenderObject(BuildContext context) {
    return _RenderTestLeaderLayerWidget(
      link: link,
    );
  }

  @override
  void updateRenderObject(BuildContext context, _RenderTestLeaderLayerWidget renderObject) {
    renderObject.link = link;
  }
}

class _RenderTestLeaderLayerWidget extends RenderProxyBox {
  _RenderTestLeaderLayerWidget({
    LayerLink? link,
    RenderBox? child,
  }) : _link = link,
        super(child);

  LayerLink? get link => _link;
  LayerLink? _link;
  set link(LayerLink? value) {
    if (_link == value) {
      return;
    }
    _link = value;
    markNeedsPaint();
  }

  @override
  bool get isRepaintBoundary => true;

  @override
  void paint(PaintingContext context, Offset offset) {
    super.paint(context, offset);
    if (_link != null) {
      context.pushLayer(LeaderLayer(link: _link!, offset: offset),(_, __){}, Offset.zero);
    }
  }
}