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

5 6 7 8 9 10
// TODO(gspencergoog): Remove this tag once this test's state leaks/test
// dependencies have been fixed.
// https://github.com/flutter/flutter/issues/85160
// Fails with "flutter test --test-randomize-ordering-seed=123"
@Tags(<String>['no-shuffle'])

11
import 'package:flutter/cupertino.dart';
12
import 'package:flutter/foundation.dart';
13
import 'package:flutter/material.dart';
14
import 'package:flutter/rendering.dart';
15
import 'package:flutter/services.dart';
16 17
import 'package:flutter_test/flutter_test.dart';

18 19
import '../rendering/mock_canvas.dart';

20
class StateMarker extends StatefulWidget {
21
  const StateMarker({ super.key, this.child });
22

23
  final Widget? child;
24 25

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

class StateMarkerState extends State<StateMarker> {
30
  late String marker;
31 32 33

  @override
  Widget build(BuildContext context) {
34
    if (widget.child != null) {
35
      return widget.child!;
36
    }
37
    return Container();
38 39 40
  }
}

41 42 43
void main() {
  testWidgets('Can nest apps', (WidgetTester tester) async {
    await tester.pumpWidget(
44
      const MaterialApp(
45
        home: MaterialApp(
46
          home: Text('Home sweet home'),
47 48
        ),
      ),
49 50 51 52 53 54
    );

    expect(find.text('Home sweet home'), findsOneWidget);
  });

  testWidgets('Focus handling', (WidgetTester tester) async {
55 56 57 58 59
    final FocusNode focusNode = FocusNode();
    await tester.pumpWidget(MaterialApp(
      home: Material(
        child: Center(
          child: TextField(focusNode: focusNode, autofocus: true),
60 61
        ),
      ),
62 63
    ));

64
    expect(focusNode.hasFocus, isTrue);
65
  });
66

67
  testWidgets('Can place app inside FocusScope', (WidgetTester tester) async {
68
    final FocusScopeNode focusScopeNode = FocusScopeNode();
69

70
    await tester.pumpWidget(FocusScope(
71 72
      autofocus: true,
      node: focusScopeNode,
73 74
      child: const MaterialApp(
        home: Text('Home'),
75 76 77 78 79 80
      ),
    ));

    expect(find.text('Home'), findsOneWidget);
  });

81 82
  testWidgets('Can show grid without losing sync', (WidgetTester tester) async {
    await tester.pumpWidget(
83 84
      const MaterialApp(
        home: StateMarker(),
85
      ),
86 87
    );

88
    final StateMarkerState state1 = tester.state(find.byType(StateMarker));
89 90 91
    state1.marker = 'original';

    await tester.pumpWidget(
92
      const MaterialApp(
93
        debugShowMaterialGrid: true,
94
        home: StateMarker(),
95
      ),
96 97
    );

98
    final StateMarkerState state2 = tester.state(find.byType(StateMarker));
99 100 101
    expect(state1, equals(state2));
    expect(state2.marker, equals('original'));
  });
102

103
  testWidgets('Do not rebuild page during a route transition', (WidgetTester tester) async {
104 105
    int buildCounter = 0;
    await tester.pumpWidget(
106 107
      MaterialApp(
        home: Builder(
108
          builder: (BuildContext context) {
109
            return Material(
110
              child: ElevatedButton(
111
                child: const Text('X'),
112
                onPressed: () { Navigator.of(context).pushNamed('/next'); },
113
              ),
114
            );
115
          },
116 117 118
        ),
        routes: <String, WidgetBuilder>{
          '/next': (BuildContext context) {
119
            return Builder(
120 121
              builder: (BuildContext context) {
                ++buildCounter;
122
                return const Text('Y');
123
              },
124
            );
125 126 127
          },
        },
      ),
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
    );

    expect(buildCounter, 0);
    await tester.tap(find.text('X'));
    expect(buildCounter, 0);
    await tester.pump();
    expect(buildCounter, 1);
    await tester.pump(const Duration(milliseconds: 10));
    expect(buildCounter, 1);
    await tester.pump(const Duration(milliseconds: 10));
    expect(buildCounter, 1);
    await tester.pump(const Duration(milliseconds: 10));
    expect(buildCounter, 1);
    await tester.pump(const Duration(milliseconds: 10));
    expect(buildCounter, 1);
    await tester.pump(const Duration(seconds: 1));
144
    expect(buildCounter, 1);
145
    expect(find.text('Y'), findsOneWidget);
146 147
  });

148 149 150
  testWidgets('Do rebuild the home page if it changes', (WidgetTester tester) async {
    int buildCounter = 0;
    await tester.pumpWidget(
151 152
      MaterialApp(
        home: Builder(
153 154 155
          builder: (BuildContext context) {
            ++buildCounter;
            return const Text('A');
156
          },
157 158 159 160 161 162
        ),
      ),
    );
    expect(buildCounter, 1);
    expect(find.text('A'), findsOneWidget);
    await tester.pumpWidget(
163 164
      MaterialApp(
        home: Builder(
165 166 167
          builder: (BuildContext context) {
            ++buildCounter;
            return const Text('B');
168
          },
169 170 171 172 173 174 175 176 177
        ),
      ),
    );
    expect(buildCounter, 2);
    expect(find.text('B'), findsOneWidget);
  });

  testWidgets('Do not rebuild the home page if it does not actually change', (WidgetTester tester) async {
    int buildCounter = 0;
178
    final Widget home = Builder(
179 180 181
      builder: (BuildContext context) {
        ++buildCounter;
        return const Placeholder();
182
      },
183 184
    );
    await tester.pumpWidget(
185
      MaterialApp(
186 187 188 189 190
        home: home,
      ),
    );
    expect(buildCounter, 1);
    await tester.pumpWidget(
191
      MaterialApp(
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
        home: home,
      ),
    );
    expect(buildCounter, 1);
  });

  testWidgets('Do rebuild pages that come from the routes table if the MaterialApp changes', (WidgetTester tester) async {
    int buildCounter = 0;
    final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{
      '/': (BuildContext context) {
        ++buildCounter;
        return const Placeholder();
      },
    };
    await tester.pumpWidget(
207
      MaterialApp(
208 209 210 211 212
        routes: routes,
      ),
    );
    expect(buildCounter, 1);
    await tester.pumpWidget(
213
      MaterialApp(
214 215 216 217 218 219
        routes: routes,
      ),
    );
    expect(buildCounter, 2);
  });

220
  testWidgets('Cannot pop the initial route', (WidgetTester tester) async {
221
    await tester.pumpWidget(const MaterialApp(home: Text('Home')));
222 223 224

    expect(find.text('Home'), findsOneWidget);

225 226
    final NavigatorState navigator = tester.state(find.byType(Navigator));
    final bool result = await navigator.maybePop();
227 228 229 230 231

    expect(result, isFalse);

    expect(find.text('Home'), findsOneWidget);
  });
232 233

  testWidgets('Default initialRoute', (WidgetTester tester) async {
234
    await tester.pumpWidget(MaterialApp(routes: <String, WidgetBuilder>{
235 236 237 238 239 240
      '/': (BuildContext context) => const Text('route "/"'),
    }));

    expect(find.text('route "/"'), findsOneWidget);
  });

241
  testWidgets('One-step initial route', (WidgetTester tester) async {
242
    await tester.pumpWidget(
243
      MaterialApp(
244 245
        initialRoute: '/a',
        routes: <String, WidgetBuilder>{
246
          '/': (BuildContext context) => const Text('route "/"'),
247
          '/a': (BuildContext context) => const Text('route "/a"'),
248 249
          '/a/b': (BuildContext context) => const Text('route "/a/b"'),
          '/b': (BuildContext context) => const Text('route "/b"'),
250
        },
251
      ),
252 253
    );

254
    expect(find.text('route "/"', skipOffstage: false), findsOneWidget);
255
    expect(find.text('route "/a"'), findsOneWidget);
256 257
    expect(find.text('route "/a/b"', skipOffstage: false), findsNothing);
    expect(find.text('route "/b"', skipOffstage: false), findsNothing);
258 259
  });

260
  testWidgets('Return value from pop is correct', (WidgetTester tester) async {
261
    late Future<Object?> result;
262
    await tester.pumpWidget(
263 264
        MaterialApp(
          home: Builder(
265 266 267 268 269 270 271 272 273 274
            builder: (BuildContext context) {
              return Material(
                child: ElevatedButton(
                    child: const Text('X'),
                    onPressed: () async {
                      result = Navigator.of(context).pushNamed<Object?>('/a');
                    },
                ),
              );
            },
275 276 277
          ),
          routes: <String, WidgetBuilder>{
            '/a': (BuildContext context) {
278
              return Material(
279
                child: ElevatedButton(
280 281
                  child: const Text('Y'),
                  onPressed: () {
282
                    Navigator.of(context).pop('all done');
283 284 285
                  },
                ),
              );
286
            },
287
          },
288
        ),
289 290 291 292 293 294 295 296 297 298 299
    );
    await tester.tap(find.text('X'));
    await tester.pump();
    await tester.pump(const Duration(seconds: 1));
    expect(find.text('Y'), findsOneWidget);
    await tester.tap(find.text('Y'));
    await tester.pump();

    expect(await result, equals('all done'));
  });

300
  testWidgets('Two-step initial route', (WidgetTester tester) async {
301 302 303
    final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{
      '/': (BuildContext context) => const Text('route "/"'),
      '/a': (BuildContext context) => const Text('route "/a"'),
304
      '/a/b': (BuildContext context) => const Text('route "/a/b"'),
305 306 307 308
      '/b': (BuildContext context) => const Text('route "/b"'),
    };

    await tester.pumpWidget(
309
      MaterialApp(
310
        initialRoute: '/a/b',
311
        routes: routes,
312
      ),
313
    );
314 315
    expect(find.text('route "/"', skipOffstage: false), findsOneWidget);
    expect(find.text('route "/a"', skipOffstage: false), findsOneWidget);
316
    expect(find.text('route "/a/b"'), findsOneWidget);
317
    expect(find.text('route "/b"', skipOffstage: false), findsNothing);
318 319 320 321 322 323 324 325 326 327 328
  });

  testWidgets('Initial route with missing step', (WidgetTester tester) async {
    final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{
      '/': (BuildContext context) => const Text('route "/"'),
      '/a': (BuildContext context) => const Text('route "/a"'),
      '/a/b': (BuildContext context) => const Text('route "/a/b"'),
      '/b': (BuildContext context) => const Text('route "/b"'),
    };

    await tester.pumpWidget(
329
      MaterialApp(
330 331
        initialRoute: '/a/b/c',
        routes: routes,
332
      ),
333 334
    );
    final dynamic exception = tester.takeException();
Dan Field's avatar
Dan Field committed
335
    expect(exception, isA<String>());
336 337 338 339 340 341 342
    if (exception is String) {
      expect(exception.startsWith('Could not navigate to initial route.'), isTrue);
      expect(find.text('route "/"'), findsOneWidget);
      expect(find.text('route "/a"'), findsNothing);
      expect(find.text('route "/a/b"'), findsNothing);
      expect(find.text('route "/b"'), findsNothing);
    }
343 344 345 346 347 348 349 350 351 352
  });

  testWidgets('Make sure initialRoute is only used the first time', (WidgetTester tester) async {
    final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{
      '/': (BuildContext context) => const Text('route "/"'),
      '/a': (BuildContext context) => const Text('route "/a"'),
      '/b': (BuildContext context) => const Text('route "/b"'),
    };

    await tester.pumpWidget(
353
      MaterialApp(
354 355
        initialRoute: '/a',
        routes: routes,
356
      ),
357
    );
358
    expect(find.text('route "/"', skipOffstage: false), findsOneWidget);
359
    expect(find.text('route "/a"'), findsOneWidget);
360
    expect(find.text('route "/b"', skipOffstage: false), findsNothing);
361

362
    // changing initialRoute has no effect
363
    await tester.pumpWidget(
364
      MaterialApp(
365 366
        initialRoute: '/b',
        routes: routes,
367
      ),
368
    );
369
    expect(find.text('route "/"', skipOffstage: false), findsOneWidget);
370
    expect(find.text('route "/a"'), findsOneWidget);
371
    expect(find.text('route "/b"', skipOffstage: false), findsNothing);
372

373
    // removing it has no effect
374
    await tester.pumpWidget(MaterialApp(routes: routes));
375
    expect(find.text('route "/"', skipOffstage: false), findsOneWidget);
376
    expect(find.text('route "/a"'), findsOneWidget);
377
    expect(find.text('route "/b"', skipOffstage: false), findsNothing);
378
  });
379 380 381 382

  testWidgets('onGenerateRoute / onUnknownRoute', (WidgetTester tester) async {
    final List<String> log = <String>[];
    await tester.pumpWidget(
383
      MaterialApp(
384 385
        onGenerateRoute: (RouteSettings settings) {
          log.add('onGenerateRoute ${settings.name}');
386
          return null;
387 388 389
        },
        onUnknownRoute: (RouteSettings settings) {
          log.add('onUnknownRoute ${settings.name}');
390
          return null;
391
        },
392
      ),
393 394 395
    );
    expect(tester.takeException(), isFlutterError);
    expect(log, <String>['onGenerateRoute /', 'onUnknownRoute /']);
396 397 398 399

    // Work-around for https://github.com/flutter/flutter/issues/65655.
    await tester.pumpWidget(Container());
    expect(tester.takeException(), isAssertionError);
400
  });
401

402 403 404 405
  testWidgets('MaterialApp with builder and no route information works.', (WidgetTester tester) async {
    // Regression test for https://github.com/flutter/flutter/issues/18904
    await tester.pumpWidget(
      MaterialApp(
406
        builder: (BuildContext context, Widget? child) {
407 408 409 410 411 412
          return const SizedBox();
        },
      ),
    );
  });

413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446
  testWidgets("WidgetsApp don't rebuild routes when MediaQuery updates", (WidgetTester tester) async {
    // Regression test for https://github.com/flutter/flutter/issues/37878
    int routeBuildCount = 0;
    int dependentBuildCount = 0;

    await tester.pumpWidget(WidgetsApp(
      color: const Color.fromARGB(255, 255, 255, 255),
      onGenerateRoute: (_) {
        return PageRouteBuilder<void>(pageBuilder: (_, __, ___) {
          routeBuildCount++;
          return Builder(
            builder: (BuildContext context) {
              dependentBuildCount++;
              MediaQuery.of(context);
              return Container();
            },
          );
        });
      },
    ));

    expect(routeBuildCount, equals(1));
    expect(dependentBuildCount, equals(1));

    // didChangeMetrics
    tester.binding.window.physicalSizeTestValue = const Size(42, 42);
    addTearDown(tester.binding.window.clearPhysicalSizeTestValue);

    await tester.pump();

    expect(routeBuildCount, equals(1));
    expect(dependentBuildCount, equals(2));

    // didChangeTextScaleFactor
447 448
    tester.binding.platformDispatcher.textScaleFactorTestValue = 42;
    addTearDown(tester.binding.platformDispatcher.clearTextScaleFactorTestValue);
449 450 451 452 453 454 455

    await tester.pump();

    expect(routeBuildCount, equals(1));
    expect(dependentBuildCount, equals(3));

    // didChangePlatformBrightness
456 457
    tester.binding.platformDispatcher.platformBrightnessTestValue = Brightness.dark;
    addTearDown(tester.binding.platformDispatcher.clearPlatformBrightnessTestValue);
458 459 460 461 462 463 464

    await tester.pump();

    expect(routeBuildCount, equals(1));
    expect(dependentBuildCount, equals(4));

    // didChangeAccessibilityFeatures
465 466
    tester.binding.platformDispatcher.accessibilityFeaturesTestValue = FakeAccessibilityFeatures.allOn;
    addTearDown(tester.binding.platformDispatcher.clearAccessibilityFeaturesTestValue);
467 468 469 470 471 472 473

    await tester.pump();

    expect(routeBuildCount, equals(1));
    expect(dependentBuildCount, equals(5));
  });

474
  testWidgets('Can get text scale from media query', (WidgetTester tester) async {
475
    double? textScaleFactor;
476 477
    await tester.pumpWidget(MaterialApp(
      home: Builder(builder:(BuildContext context) {
478
        textScaleFactor = MediaQuery.of(context).textScaleFactor;
479
        return Container();
480 481 482 483 484
      }),
    ));
    expect(textScaleFactor, isNotNull);
    expect(textScaleFactor, equals(1.0));
  });
485 486

  testWidgets('MaterialApp.navigatorKey', (WidgetTester tester) async {
487 488
    final GlobalKey<NavigatorState> key = GlobalKey<NavigatorState>();
    await tester.pumpWidget(MaterialApp(
489 490 491 492
      navigatorKey: key,
      color: const Color(0xFF112233),
      home: const Placeholder(),
    ));
Dan Field's avatar
Dan Field committed
493
    expect(key.currentState, isA<NavigatorState>());
494 495 496
    await tester.pumpWidget(const MaterialApp(
      color: Color(0xFF112233),
      home: Placeholder(),
497 498
    ));
    expect(key.currentState, isNull);
499
    await tester.pumpWidget(MaterialApp(
500 501 502 503
      navigatorKey: key,
      color: const Color(0xFF112233),
      home: const Placeholder(),
    ));
Dan Field's avatar
Dan Field committed
504
    expect(key.currentState, isA<NavigatorState>());
505
  });
506 507 508 509 510 511 512 513

  testWidgets('Has default material and cupertino localizations', (WidgetTester tester) async {
    await tester.pumpWidget(
      MaterialApp(
        home: Builder(
          builder: (BuildContext context) {
            return Column(
              children: <Widget>[
514 515
                Text(MaterialLocalizations.of(context).selectAllButtonLabel),
                Text(CupertinoLocalizations.of(context).selectAllButtonLabel),
516 517 518 519 520 521 522 523
              ],
            );
          },
        ),
      ),
    );

    // Default US "select all" text.
524
    expect(find.text('Select all'), findsOneWidget);
525 526 527
    // Default Cupertino US "select all" text.
    expect(find.text('Select All'), findsOneWidget);
  });
528

529 530
  testWidgets('MaterialApp uses regular theme when themeMode is light', (WidgetTester tester) async {
    // Mock the Window to explicitly report a light platformBrightness.
531
    tester.binding.platformDispatcher.platformBrightnessTestValue = Brightness.light;
532

533
    late ThemeData appliedTheme;
534 535 536
    await tester.pumpWidget(
      MaterialApp(
        theme: ThemeData(
537
          brightness: Brightness.light,
538 539 540 541 542 543 544
        ),
        darkTheme: ThemeData(
          brightness: Brightness.dark,
        ),
        themeMode: ThemeMode.light,
        home: Builder(
          builder: (BuildContext context) {
545
            appliedTheme = Theme.of(context);
546 547 548 549 550 551 552 553
            return const SizedBox();
          },
        ),
      ),
    );
    expect(appliedTheme.brightness, Brightness.light);

    // Mock the Window to explicitly report a dark platformBrightness.
554
    tester.binding.platformDispatcher.platformBrightnessTestValue = Brightness.dark;
555 556 557
    await tester.pumpWidget(
      MaterialApp(
        theme: ThemeData(
558
          brightness: Brightness.light,
559 560 561 562 563 564 565
        ),
        darkTheme: ThemeData(
          brightness: Brightness.dark,
        ),
        themeMode: ThemeMode.light,
        home: Builder(
          builder: (BuildContext context) {
566
            appliedTheme = Theme.of(context);
567 568 569 570 571 572 573 574 575 576
            return const SizedBox();
          },
        ),
      ),
    );
    expect(appliedTheme.brightness, Brightness.light);
  });

  testWidgets('MaterialApp uses darkTheme when themeMode is dark', (WidgetTester tester) async {
    // Mock the Window to explicitly report a light platformBrightness.
577
    tester.binding.platformDispatcher.platformBrightnessTestValue = Brightness.light;
578

579
    late ThemeData appliedTheme;
580 581 582
    await tester.pumpWidget(
      MaterialApp(
        theme: ThemeData(
583
          brightness: Brightness.light,
584 585 586 587 588 589 590
        ),
        darkTheme: ThemeData(
          brightness: Brightness.dark,
        ),
        themeMode: ThemeMode.dark,
        home: Builder(
          builder: (BuildContext context) {
591
            appliedTheme = Theme.of(context);
592 593 594 595 596 597 598 599
            return const SizedBox();
          },
        ),
      ),
    );
    expect(appliedTheme.brightness, Brightness.dark);

    // Mock the Window to explicitly report a dark platformBrightness.
600
    tester.binding.platformDispatcher.platformBrightnessTestValue = Brightness.dark;
601 602 603
    await tester.pumpWidget(
      MaterialApp(
        theme: ThemeData(
604
          brightness: Brightness.light,
605 606 607 608 609 610 611
        ),
        darkTheme: ThemeData(
          brightness: Brightness.dark,
        ),
        themeMode: ThemeMode.dark,
        home: Builder(
          builder: (BuildContext context) {
612
            appliedTheme = Theme.of(context);
613 614 615 616 617 618 619 620 621
            return const SizedBox();
          },
        ),
      ),
    );
    expect(appliedTheme.brightness, Brightness.dark);
  });

  testWidgets('MaterialApp uses regular theme when themeMode is system and platformBrightness is light', (WidgetTester tester) async {
622 623
    // Mock the Window to explicitly report a light platformBrightness.
    final TestWidgetsFlutterBinding binding = tester.binding;
624
    binding.platformDispatcher.platformBrightnessTestValue = Brightness.light;
625

626
    late ThemeData appliedTheme;
627 628 629 630

    await tester.pumpWidget(
      MaterialApp(
        theme: ThemeData(
631
          brightness: Brightness.light,
632 633 634 635 636 637
        ),
        darkTheme: ThemeData(
          brightness: Brightness.dark,
        ),
        home: Builder(
          builder: (BuildContext context) {
638
            appliedTheme = Theme.of(context);
639 640 641 642 643 644 645 646 647
            return const SizedBox();
          },
        ),
      ),
    );

    expect(appliedTheme.brightness, Brightness.light);
  });

648 649
  testWidgets('MaterialApp uses darkTheme when themeMode is system and platformBrightness is dark', (WidgetTester tester) async {
    // Mock the Window to explicitly report a dark platformBrightness.
650
    tester.binding.platformDispatcher.platformBrightnessTestValue = Brightness.dark;
651

652
    late ThemeData appliedTheme;
653 654 655
    await tester.pumpWidget(
      MaterialApp(
        theme: ThemeData(
656
          brightness: Brightness.light,
657 658 659 660 661 662
        ),
        darkTheme: ThemeData(
          brightness: Brightness.dark,
        ),
        home: Builder(
          builder: (BuildContext context) {
663
            appliedTheme = Theme.of(context);
664 665 666 667 668 669 670 671
            return const SizedBox();
          },
        ),
      ),
    );
    expect(appliedTheme.brightness, Brightness.dark);
  });

672 673 674
  testWidgets('MaterialApp uses light theme when platformBrightness is dark but no dark theme is provided', (WidgetTester tester) async {
    // Mock the Window to explicitly report a dark platformBrightness.
    final TestWidgetsFlutterBinding binding = tester.binding;
675
    binding.platformDispatcher.platformBrightnessTestValue = Brightness.dark;
676

677
    late ThemeData appliedTheme;
678 679 680 681

    await tester.pumpWidget(
      MaterialApp(
        theme: ThemeData(
682
          brightness: Brightness.light,
683 684 685
        ),
        home: Builder(
          builder: (BuildContext context) {
686
            appliedTheme = Theme.of(context);
687 688 689 690 691 692 693 694 695 696 697 698
            return const SizedBox();
          },
        ),
      ),
    );

    expect(appliedTheme.brightness, Brightness.light);
  });

  testWidgets('MaterialApp uses fallback light theme when platformBrightness is dark but no theme is provided at all', (WidgetTester tester) async {
    // Mock the Window to explicitly report a dark platformBrightness.
    final TestWidgetsFlutterBinding binding = tester.binding;
699
    binding.platformDispatcher.platformBrightnessTestValue = Brightness.dark;
700

701
    late ThemeData appliedTheme;
702 703 704 705 706

    await tester.pumpWidget(
      MaterialApp(
        home: Builder(
          builder: (BuildContext context) {
707
            appliedTheme = Theme.of(context);
708 709 710 711 712 713 714 715 716 717 718 719
            return const SizedBox();
          },
        ),
      ),
    );

    expect(appliedTheme.brightness, Brightness.light);
  });

  testWidgets('MaterialApp uses fallback light theme when platformBrightness is light and a dark theme is provided', (WidgetTester tester) async {
    // Mock the Window to explicitly report a dark platformBrightness.
    final TestWidgetsFlutterBinding binding = tester.binding;
720
    binding.platformDispatcher.platformBrightnessTestValue = Brightness.light;
721

722
    late ThemeData appliedTheme;
723 724 725 726 727 728 729 730

    await tester.pumpWidget(
      MaterialApp(
        darkTheme: ThemeData(
          brightness: Brightness.dark,
        ),
        home: Builder(
          builder: (BuildContext context) {
731
            appliedTheme = Theme.of(context);
732 733 734 735 736 737 738 739 740 741 742 743
            return const SizedBox();
          },
        ),
      ),
    );

    expect(appliedTheme.brightness, Brightness.light);
  });

  testWidgets('MaterialApp uses dark theme when platformBrightness is dark', (WidgetTester tester) async {
    // Mock the Window to explicitly report a dark platformBrightness.
    final TestWidgetsFlutterBinding binding = tester.binding;
744
    binding.platformDispatcher.platformBrightnessTestValue = Brightness.dark;
745

746
    late ThemeData appliedTheme;
747 748 749 750

    await tester.pumpWidget(
      MaterialApp(
        theme: ThemeData(
751
          brightness: Brightness.light,
752 753 754 755 756 757
        ),
        darkTheme: ThemeData(
          brightness: Brightness.dark,
        ),
        home: Builder(
          builder: (BuildContext context) {
758
            appliedTheme = Theme.of(context);
759 760 761 762 763 764 765 766 767
            return const SizedBox();
          },
        ),
      ),
    );

    expect(appliedTheme.brightness, Brightness.dark);
  });

768
  testWidgets('MaterialApp uses high contrast theme when appropriate', (WidgetTester tester) async {
769 770
    tester.binding.platformDispatcher.platformBrightnessTestValue = Brightness.light;
    tester.binding.platformDispatcher.accessibilityFeaturesTestValue = FakeAccessibilityFeatures.allOn;
771

772
    late ThemeData appliedTheme;
773 774 775 776 777 778 779 780 781 782 783

    await tester.pumpWidget(
      MaterialApp(
        theme: ThemeData(
          primaryColor: Colors.lightBlue,
        ),
        highContrastTheme: ThemeData(
          primaryColor: Colors.blue,
        ),
        home: Builder(
          builder: (BuildContext context) {
784
            appliedTheme = Theme.of(context);
785 786 787 788 789 790 791
            return const SizedBox();
          },
        ),
      ),
    );

    expect(appliedTheme.primaryColor, Colors.blue);
792
    tester.binding.platformDispatcher.clearAccessibilityFeaturesTestValue();
793 794 795
  });

  testWidgets('MaterialApp uses high contrast dark theme when appropriate', (WidgetTester tester) async {
796 797
    tester.binding.platformDispatcher.platformBrightnessTestValue = Brightness.dark;
    tester.binding.platformDispatcher.accessibilityFeaturesTestValue = FakeAccessibilityFeatures.allOn;
798

799
    late ThemeData appliedTheme;
800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816

    await tester.pumpWidget(
      MaterialApp(
        theme: ThemeData(
          primaryColor: Colors.lightBlue,
        ),
        darkTheme: ThemeData(
          primaryColor: Colors.lightGreen,
        ),
        highContrastTheme: ThemeData(
          primaryColor: Colors.blue,
        ),
        highContrastDarkTheme: ThemeData(
          primaryColor: Colors.green,
        ),
        home: Builder(
          builder: (BuildContext context) {
817
            appliedTheme = Theme.of(context);
818 819 820 821 822 823 824
            return const SizedBox();
          },
        ),
      ),
    );

    expect(appliedTheme.primaryColor, Colors.green);
825
    tester.binding.platformDispatcher.clearAccessibilityFeaturesTestValue();
826 827
  });

828
  testWidgets('MaterialApp uses dark theme when no high contrast dark theme is provided', (WidgetTester tester) async {
829 830
    tester.binding.platformDispatcher.platformBrightnessTestValue = Brightness.dark;
    tester.binding.platformDispatcher.accessibilityFeaturesTestValue = FakeAccessibilityFeatures.allOn;
831

832
    late ThemeData appliedTheme;
833 834 835 836 837 838 839 840 841 842 843

    await tester.pumpWidget(
      MaterialApp(
        theme: ThemeData(
          primaryColor: Colors.lightBlue,
        ),
        darkTheme: ThemeData(
          primaryColor: Colors.lightGreen,
        ),
        home: Builder(
          builder: (BuildContext context) {
844
            appliedTheme = Theme.of(context);
845 846 847 848 849 850 851
            return const SizedBox();
          },
        ),
      ),
    );

    expect(appliedTheme.primaryColor, Colors.lightGreen);
852 853
    tester.binding.platformDispatcher.clearAccessibilityFeaturesTestValue();
    tester.binding.platformDispatcher.clearPlatformBrightnessTestValue();
854 855
  });

856 857 858
  testWidgets('MaterialApp switches themes when the Window platformBrightness changes.', (WidgetTester tester) async {
    // Mock the Window to explicitly report a light platformBrightness.
    final TestWidgetsFlutterBinding binding = tester.binding;
859
    binding.platformDispatcher.platformBrightnessTestValue = Brightness.light;
860

861 862
    ThemeData? themeBeforeBrightnessChange;
    ThemeData? themeAfterBrightnessChange;
863 864 865 866

    await tester.pumpWidget(
      MaterialApp(
        theme: ThemeData(
867
          brightness: Brightness.light,
868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886
        ),
        darkTheme: ThemeData(
          brightness: Brightness.dark,
        ),
        home: Builder(
          builder: (BuildContext context) {
            if (themeBeforeBrightnessChange == null) {
              themeBeforeBrightnessChange = Theme.of(context);
            } else {
              themeAfterBrightnessChange = Theme.of(context);
            }
            return const SizedBox();
          },
        ),
      ),
    );

    // Switch the platformBrightness from light to dark and pump the widget tree
    // to process changes.
887
    binding.platformDispatcher.platformBrightnessTestValue = Brightness.dark;
888 889
    await tester.pumpAndSettle();

890 891
    expect(themeBeforeBrightnessChange!.brightness, Brightness.light);
    expect(themeAfterBrightnessChange!.brightness, Brightness.dark);
892
  });
893

894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924
  testWidgets('MaterialApp provides default overscroll color', (WidgetTester tester) async {
    Future<void> slowDrag(WidgetTester tester, Offset start, Offset offset) async {
      final TestGesture gesture = await tester.startGesture(start);
      for (int index = 0; index < 10; index += 1) {
        await gesture.moveBy(offset);
        await tester.pump(const Duration(milliseconds: 20));
      }
      await gesture.up();
    }

    // The overscroll color should be a transparent version of the colorScheme's
    // secondary color.
    const Color secondaryColor = Color(0xff008800);
    final Color glowSecondaryColor = secondaryColor.withOpacity(0.05);
    final ThemeData theme = ThemeData.from(
      colorScheme: const ColorScheme.light().copyWith(secondary: secondaryColor),
    );
    await tester.pumpWidget(
      MaterialApp(
        theme: theme,
        home: const SingleChildScrollView(
          child: SizedBox(height: 2000.0),
        ),
      ),
    );

    final RenderObject painter = tester.renderObject(find.byType(CustomPaint).first);
    await slowDrag(tester, const Offset(200.0, 200.0), const Offset(0.0, 5.0));
    expect(painter, paints..circle(color: glowSecondaryColor));
  });

925 926 927 928 929 930 931 932 933 934 935 936
  testWidgets('MaterialApp can customize initial routes', (WidgetTester tester) async {
    final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();
    await tester.pumpWidget(
      MaterialApp(
        navigatorKey: navigatorKey,
        onGenerateInitialRoutes: (String initialRoute) {
          expect(initialRoute, '/abc');
          return <Route<void>>[
            PageRouteBuilder<void>(
              pageBuilder: (
                BuildContext context,
                Animation<double> animation,
937 938
                Animation<double> secondaryAnimation,
              ) {
939
                return const Text('non-regular page one');
940
              },
941 942 943 944 945
            ),
            PageRouteBuilder<void>(
              pageBuilder: (
                BuildContext context,
                Animation<double> animation,
946 947
                Animation<double> secondaryAnimation,
              ) {
948
                return const Text('non-regular page two');
949
              },
950 951 952 953 954 955 956 957
            ),
          ];
        },
        initialRoute: '/abc',
        routes: <String, WidgetBuilder>{
          '/': (BuildContext context) => const Text('regular page one'),
          '/abc': (BuildContext context) => const Text('regular page two'),
        },
958
      ),
959 960 961 962 963
    );
    expect(find.text('non-regular page two'), findsOneWidget);
    expect(find.text('non-regular page one'), findsNothing);
    expect(find.text('regular page one'), findsNothing);
    expect(find.text('regular page two'), findsNothing);
964
    navigatorKey.currentState!.pop();
965 966 967 968 969 970
    await tester.pumpAndSettle();
    expect(find.text('non-regular page two'), findsNothing);
    expect(find.text('non-regular page one'), findsOneWidget);
    expect(find.text('regular page one'), findsNothing);
    expect(find.text('regular page two'), findsNothing);
  });
971 972 973

  testWidgets('MaterialApp does create HeroController with the MaterialRectArcTween', (WidgetTester tester) async {
    final HeroController controller = MaterialApp.createMaterialHeroController();
974
    final Tween<Rect?> tween = controller.createRectTween!(
975
      const Rect.fromLTRB(0.0, 0.0, 10.0, 10.0),
976
      const Rect.fromLTRB(0.0, 0.0, 20.0, 20.0),
977 978 979
    );
    expect(tween, isA<MaterialRectArcTween>());
  });
980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995

  testWidgets('MaterialApp.navigatorKey can be updated', (WidgetTester tester) async {
    final GlobalKey<NavigatorState> key1 = GlobalKey<NavigatorState>();
    await tester.pumpWidget(MaterialApp(
      navigatorKey: key1,
      home: const Placeholder(),
    ));
    expect(key1.currentState, isA<NavigatorState>());
    final GlobalKey<NavigatorState> key2 = GlobalKey<NavigatorState>();
    await tester.pumpWidget(MaterialApp(
      navigatorKey: key2,
      home: const Placeholder(),
    ));
    expect(key2.currentState, isA<NavigatorState>());
    expect(key1.currentState, isNull);
  });
996 997 998 999 1000 1001 1002 1003 1004

  testWidgets('MaterialApp.router works', (WidgetTester tester) async {
    final PlatformRouteInformationProvider provider = PlatformRouteInformationProvider(
      initialRouteInformation: const RouteInformation(
        location: 'initial',
      ),
    );
    final SimpleNavigatorRouterDelegate delegate = SimpleNavigatorRouterDelegate(
      builder: (BuildContext context, RouteInformation information) {
1005
        return Text(information.location!);
1006 1007 1008 1009 1010 1011
      },
      onPopPage: (Route<void> route, void result, SimpleNavigatorRouterDelegate delegate) {
        delegate.routeInformation = const RouteInformation(
          location: 'popped',
        );
        return route.didPop(result);
1012
      },
1013 1014 1015 1016 1017 1018 1019 1020 1021 1022
    );
    await tester.pumpWidget(MaterialApp.router(
      routeInformationProvider: provider,
      routeInformationParser: SimpleRouteInformationParser(),
      routerDelegate: delegate,
    ));
    expect(find.text('initial'), findsOneWidget);

    // Simulate android back button intent.
    final ByteData message = const JSONMethodCodec().encodeMethodCall(const MethodCall('popRoute'));
1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126
    await ServicesBinding.instance.defaultBinaryMessenger.handlePlatformMessage('flutter/navigation', message, (_) { });
    await tester.pumpAndSettle();
    expect(find.text('popped'), findsOneWidget);
  });

  testWidgets('MaterialApp.router route information parser is optional', (WidgetTester tester) async {
    final SimpleNavigatorRouterDelegate delegate = SimpleNavigatorRouterDelegate(
      builder: (BuildContext context, RouteInformation information) {
        return Text(information.location!);
      },
      onPopPage: (Route<void> route, void result, SimpleNavigatorRouterDelegate delegate) {
        delegate.routeInformation = const RouteInformation(
          location: 'popped',
        );
        return route.didPop(result);
      },
    );
    delegate.routeInformation = const RouteInformation(location: 'initial');
    await tester.pumpWidget(MaterialApp.router(
      routerDelegate: delegate,
    ));
    expect(find.text('initial'), findsOneWidget);

    // Simulate android back button intent.
    final ByteData message = const JSONMethodCodec().encodeMethodCall(const MethodCall('popRoute'));
    await ServicesBinding.instance.defaultBinaryMessenger.handlePlatformMessage('flutter/navigation', message, (_) { });
    await tester.pumpAndSettle();
    expect(find.text('popped'), findsOneWidget);
  });

  testWidgets('MaterialApp.router throw if route information provider is provided but no route information parser', (WidgetTester tester) async {
    final SimpleNavigatorRouterDelegate delegate = SimpleNavigatorRouterDelegate(
      builder: (BuildContext context, RouteInformation information) {
        return Text(information.location!);
      },
      onPopPage: (Route<void> route, void result, SimpleNavigatorRouterDelegate delegate) {
        delegate.routeInformation = const RouteInformation(
          location: 'popped',
        );
        return route.didPop(result);
      },
    );
    delegate.routeInformation = const RouteInformation(location: 'initial');
    final PlatformRouteInformationProvider provider = PlatformRouteInformationProvider(
      initialRouteInformation: const RouteInformation(
        location: 'initial',
      ),
    );
    await tester.pumpWidget(MaterialApp.router(
      routeInformationProvider: provider,
      routerDelegate: delegate,
    ));
    expect(tester.takeException(), isAssertionError);
  });

  testWidgets('MaterialApp.router throw if route configuration is provided along with other delegate', (WidgetTester tester) async {
    final SimpleNavigatorRouterDelegate delegate = SimpleNavigatorRouterDelegate(
      builder: (BuildContext context, RouteInformation information) {
        return Text(information.location!);
      },
      onPopPage: (Route<void> route, void result, SimpleNavigatorRouterDelegate delegate) {
        delegate.routeInformation = const RouteInformation(
          location: 'popped',
        );
        return route.didPop(result);
      },
    );
    delegate.routeInformation = const RouteInformation(location: 'initial');
    final RouterConfig<RouteInformation> routerConfig = RouterConfig<RouteInformation>(routerDelegate: delegate);
    await tester.pumpWidget(MaterialApp.router(
      routerDelegate: delegate,
      routerConfig: routerConfig,
    ));
    expect(tester.takeException(), isAssertionError);
  });

  testWidgets('MaterialApp.router router config works', (WidgetTester tester) async {
    final RouterConfig<RouteInformation> routerConfig = RouterConfig<RouteInformation>(
        routeInformationProvider: PlatformRouteInformationProvider(
          initialRouteInformation: const RouteInformation(
            location: 'initial',
          ),
        ),
        routeInformationParser: SimpleRouteInformationParser(),
        routerDelegate: SimpleNavigatorRouterDelegate(
          builder: (BuildContext context, RouteInformation information) {
            return Text(information.location!);
          },
          onPopPage: (Route<void> route, void result, SimpleNavigatorRouterDelegate delegate) {
            delegate.routeInformation = const RouteInformation(
              location: 'popped',
            );
            return route.didPop(result);
          },
        ),
        backButtonDispatcher: RootBackButtonDispatcher()
    );
    await tester.pumpWidget(MaterialApp.router(
      routerConfig: routerConfig,
    ));
    expect(find.text('initial'), findsOneWidget);

    // Simulate android back button intent.
    final ByteData message = const JSONMethodCodec().encodeMethodCall(const MethodCall('popRoute'));
1127
    await ServicesBinding.instance.defaultBinaryMessenger.handlePlatformMessage('flutter/navigation', message, (_) { });
1128 1129 1130
    await tester.pumpAndSettle();
    expect(find.text('popped'), findsOneWidget);
  });
1131 1132

  testWidgets('MaterialApp.builder can build app without a Navigator', (WidgetTester tester) async {
1133
    Widget? builderChild;
1134
    await tester.pumpWidget(MaterialApp(
1135
      builder: (BuildContext context, Widget? child) {
1136 1137 1138 1139 1140 1141
        builderChild = child;
        return Container();
      },
    ));
    expect(builderChild, isNull);
  });
1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161

  testWidgets('MaterialApp has correct default ScrollBehavior', (WidgetTester tester) async {
    late BuildContext capturedContext;
    await tester.pumpWidget(
      MaterialApp(
        home: Builder(
          builder: (BuildContext context) {
            capturedContext = context;
            return const Placeholder();
          },
        ),
      ),
    );
    expect(ScrollConfiguration.of(capturedContext).runtimeType, MaterialScrollBehavior);
  });

  testWidgets('A ScrollBehavior can be set for MaterialApp', (WidgetTester tester) async {
    late BuildContext capturedContext;
    await tester.pumpWidget(
      MaterialApp(
1162
        scrollBehavior: const MockScrollBehavior(),
1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174
        home: Builder(
          builder: (BuildContext context) {
            capturedContext = context;
            return const Placeholder();
          },
        ),
      ),
    );
    final ScrollBehavior scrollBehavior = ScrollConfiguration.of(capturedContext);
    expect(scrollBehavior.runtimeType, MockScrollBehavior);
    expect(scrollBehavior.getScrollPhysics(capturedContext).runtimeType, NeverScrollableScrollPhysics);
  });
1175

1176 1177 1178 1179 1180 1181 1182 1183 1184
  testWidgets('ScrollBehavior default android overscroll indicator', (WidgetTester tester) async {
    await tester.pumpWidget(MaterialApp(
      scrollBehavior: const MaterialScrollBehavior(),
      home: ListView(
        children: const <Widget>[
          SizedBox(
            height: 1000.0,
            width: 1000.0,
            child: Text('Test'),
1185 1186 1187
          ),
        ],
      ),
1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202
    ));

    expect(find.byType(StretchingOverscrollIndicator), findsNothing);
    expect(find.byType(GlowingOverscrollIndicator), findsOneWidget);
  }, variant: TargetPlatformVariant.only(TargetPlatform.android));

  testWidgets('ScrollBehavior stretch android overscroll indicator', (WidgetTester tester) async {
    await tester.pumpWidget(MaterialApp(
      scrollBehavior: const MaterialScrollBehavior(androidOverscrollIndicator: AndroidOverscrollIndicator.stretch),
      home: ListView(
        children: const <Widget>[
          SizedBox(
            height: 1000.0,
            width: 1000.0,
            child: Text('Test'),
1203 1204 1205
          ),
        ],
      ),
1206 1207 1208 1209 1210 1211
    ));

    expect(find.byType(StretchingOverscrollIndicator), findsOneWidget);
    expect(find.byType(GlowingOverscrollIndicator), findsNothing);
  }, variant: TargetPlatformVariant.only(TargetPlatform.android));

1212 1213 1214
  testWidgets('ScrollBehavior stretch android overscroll indicator via useMaterial3 flag', (WidgetTester tester) async {
    await tester.pumpWidget(MaterialApp(
      theme: ThemeData(useMaterial3: true),
1215 1216 1217 1218 1219 1220 1221 1222 1223
      home: ListView(
        children: const <Widget>[
          SizedBox(
            height: 1000.0,
            width: 1000.0,
            child: Text('Test'),
          ),
        ],
      ),
1224 1225 1226 1227 1228 1229
    ));

    expect(find.byType(StretchingOverscrollIndicator), findsOneWidget);
    expect(find.byType(GlowingOverscrollIndicator), findsNothing);
  }, variant: TargetPlatformVariant.only(TargetPlatform.android));

1230 1231 1232 1233 1234 1235 1236 1237 1238 1239
  testWidgets('Overscroll indicator can be set by theme', (WidgetTester tester) async {
    await tester.pumpWidget(MaterialApp(
      // The current default is glowing, setting via the theme should override.
      theme: ThemeData().copyWith(androidOverscrollIndicator: AndroidOverscrollIndicator.stretch),
      home: ListView(
        children: const <Widget>[
          SizedBox(
            height: 1000.0,
            width: 1000.0,
            child: Text('Test'),
1240 1241 1242
          ),
        ],
      ),
1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259
    ));

    expect(find.byType(StretchingOverscrollIndicator), findsOneWidget);
    expect(find.byType(GlowingOverscrollIndicator), findsNothing);
  }, variant: TargetPlatformVariant.only(TargetPlatform.android));

  testWidgets('Overscroll indicator in MaterialScrollBehavior takes precedence over theme', (WidgetTester tester) async {
    await tester.pumpWidget(MaterialApp(
      // MaterialScrollBehavior.androidOverscrollIndicator takes precedence over theme.
      scrollBehavior: const MaterialScrollBehavior(androidOverscrollIndicator: AndroidOverscrollIndicator.stretch),
      theme: ThemeData().copyWith(androidOverscrollIndicator: AndroidOverscrollIndicator.glow),
      home: ListView(
        children: const <Widget>[
          SizedBox(
            height: 1000.0,
            width: 1000.0,
            child: Text('Test'),
1260 1261 1262
          ),
        ],
      ),
1263 1264 1265 1266 1267
    ));

    expect(find.byType(StretchingOverscrollIndicator), findsOneWidget);
    expect(find.byType(GlowingOverscrollIndicator), findsNothing);
  }, variant: TargetPlatformVariant.only(TargetPlatform.android));
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

  testWidgets(
    'ListView clip behavior updates overscroll indicator clip behavior', (WidgetTester tester) async {
      Widget buildFrame(Clip clipBehavior) {
        return MaterialApp(
          theme: ThemeData(useMaterial3: true),
          home: Column(
            children: <Widget>[
              SizedBox(
                height: 300,
                child: ListView.builder(
                  itemCount: 20,
                  clipBehavior: clipBehavior,
                  itemBuilder: (BuildContext context, int index){
                    return Padding(
                      padding: const EdgeInsets.all(10.0),
                      child: Text('Index $index'),
                    );
                  },
                ),
              ),
              Opacity(
                opacity: 0.5,
                child: Container(
                  color: const Color(0xD0FF0000),
                  height: 100,
                ),
              ),
            ],
          ),
        );
      }

      // Test default clip behavior.
      await tester.pumpWidget(buildFrame(Clip.hardEdge));

      expect(find.byType(StretchingOverscrollIndicator), findsOneWidget);
      expect(find.byType(GlowingOverscrollIndicator), findsNothing);
      expect(find.text('Index 1'), findsOneWidget);

      RenderClipRect renderClip = tester.allRenderObjects.whereType<RenderClipRect>().first;
      // Currently not clipping
      expect(renderClip.clipBehavior, equals(Clip.none));

      TestGesture gesture = await tester.startGesture(tester.getCenter(find.text('Index 1')));
      // Overscroll the start.
      await gesture.moveBy(const Offset(0.0, 200.0));
      await tester.pumpAndSettle();
      expect(find.text('Index 1'), findsOneWidget);
      expect(tester.getCenter(find.text('Index 1')).dy, greaterThan(0));
      renderClip = tester.allRenderObjects.whereType<RenderClipRect>().first;
      // Now clipping
      expect(renderClip.clipBehavior, equals(Clip.hardEdge));

      await gesture.up();
      await tester.pumpAndSettle();

      // Test custom clip behavior.
      await tester.pumpWidget(buildFrame(Clip.none));

      renderClip = tester.allRenderObjects.whereType<RenderClipRect>().first;
      // Currently not clipping
      expect(renderClip.clipBehavior, equals(Clip.none));

      gesture = await tester.startGesture(tester.getCenter(find.text('Index 1')));
      // Overscroll the start.
      await gesture.moveBy(const Offset(0.0, 200.0));
      await tester.pumpAndSettle();
      expect(find.text('Index 1'), findsOneWidget);
      expect(tester.getCenter(find.text('Index 1')).dy, greaterThan(0));
      renderClip = tester.allRenderObjects.whereType<RenderClipRect>().first;
      // Now clipping
      expect(renderClip.clipBehavior, equals(Clip.none));

      await gesture.up();
      await tester.pumpAndSettle();
  }, variant: TargetPlatformVariant.only(TargetPlatform.android));
1345

1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364
  testWidgets('When `useInheritedMediaQuery` is true an existing MediaQuery is used if one is available', (WidgetTester tester) async {
    late BuildContext capturedContext;
    final UniqueKey uniqueKey = UniqueKey();
    await tester.pumpWidget(
      MediaQuery(
        key: uniqueKey,
        data: const MediaQueryData(),
        child: MaterialApp(
          useInheritedMediaQuery: true,
          builder: (BuildContext context, Widget? child) {
            capturedContext = context;
            return const Placeholder();
          },
          color: const Color(0xFF123456),
        ),
      ),
    );
    expect(capturedContext.dependOnInheritedWidgetOfExactType<MediaQuery>()?.key, uniqueKey);
  });
1365 1366 1367
}

class MockScrollBehavior extends ScrollBehavior {
1368 1369
  const MockScrollBehavior();

1370 1371
  @override
  ScrollPhysics getScrollPhysics(BuildContext context) => const NeverScrollableScrollPhysics();
1372
}
1373

1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392
typedef SimpleRouterDelegateBuilder = Widget Function(BuildContext, RouteInformation);
typedef SimpleNavigatorRouterDelegatePopPage<T> = bool Function(Route<T> route, T result, SimpleNavigatorRouterDelegate delegate);

class SimpleRouteInformationParser extends RouteInformationParser<RouteInformation> {
  SimpleRouteInformationParser();

  @override
  Future<RouteInformation> parseRouteInformation(RouteInformation information) {
    return SynchronousFuture<RouteInformation>(information);
  }

  @override
  RouteInformation restoreRouteInformation(RouteInformation configuration) {
    return configuration;
  }
}

class SimpleNavigatorRouterDelegate extends RouterDelegate<RouteInformation> with PopNavigatorRouterDelegateMixin<RouteInformation>, ChangeNotifier {
  SimpleNavigatorRouterDelegate({
1393 1394
    required this.builder,
    required this.onPopPage,
1395 1396 1397 1398 1399 1400
  });

  @override
  GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();

  RouteInformation get routeInformation => _routeInformation;
1401
  late RouteInformation _routeInformation;
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
  set routeInformation(RouteInformation newValue) {
    _routeInformation = newValue;
    notifyListeners();
  }

  SimpleRouterDelegateBuilder builder;
  SimpleNavigatorRouterDelegatePopPage<void> onPopPage;

  @override
  Future<void> setNewRoutePath(RouteInformation configuration) {
    _routeInformation = configuration;
    return SynchronousFuture<void>(null);
  }

  bool _handlePopPage(Route<void> route, void data) {
    return onPopPage(route, data, this);
  }

  @override
  Widget build(BuildContext context) {
    return Navigator(
      key: navigatorKey,
      onPopPage: _handlePopPage,
      pages: <Page<void>>[
        // We need at least two pages for the pop to propagate through.
        // Otherwise, the navigator will bubble the pop to the system navigator.
1428 1429
        const MaterialPage<void>(
          child: Text('base'),
1430 1431
        ),
        MaterialPage<void>(
1432
          key: ValueKey<String>(routeInformation.location!),
1433
          child: builder(context, routeInformation),
1434
        ),
1435 1436 1437 1438
      ],
    );
  }
}