app_test.dart 53 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/cupertino.dart';
6
import 'package:flutter/foundation.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
import '../rendering/mock_canvas.dart';

14
class StateMarker extends StatefulWidget {
15
  const StateMarker({ super.key, this.child });
16

17
  final Widget? child;
18 19

  @override
20
  StateMarkerState createState() => StateMarkerState();
21 22 23
}

class StateMarkerState extends State<StateMarker> {
24
  late String marker;
25 26 27

  @override
  Widget build(BuildContext context) {
28
    if (widget.child != null) {
29
      return widget.child!;
30
    }
31
    return Container();
32 33 34
  }
}

35 36 37
void main() {
  testWidgets('Can nest apps', (WidgetTester tester) async {
    await tester.pumpWidget(
38
      const MaterialApp(
39
        home: MaterialApp(
40
          home: Text('Home sweet home'),
41 42
        ),
      ),
43 44 45 46 47 48
    );

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

  testWidgets('Focus handling', (WidgetTester tester) async {
49 50 51 52 53
    final FocusNode focusNode = FocusNode();
    await tester.pumpWidget(MaterialApp(
      home: Material(
        child: Center(
          child: TextField(focusNode: focusNode, autofocus: true),
54 55
        ),
      ),
56 57
    ));

58
    expect(focusNode.hasFocus, isTrue);
59
  });
60

61
  testWidgets('Can place app inside FocusScope', (WidgetTester tester) async {
62
    final FocusScopeNode focusScopeNode = FocusScopeNode();
63

64
    await tester.pumpWidget(FocusScope(
65 66
      autofocus: true,
      node: focusScopeNode,
67 68
      child: const MaterialApp(
        home: Text('Home'),
69 70 71 72 73 74
      ),
    ));

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

75 76
  testWidgets('Can show grid without losing sync', (WidgetTester tester) async {
    await tester.pumpWidget(
77 78
      const MaterialApp(
        home: StateMarker(),
79
      ),
80 81
    );

82
    final StateMarkerState state1 = tester.state(find.byType(StateMarker));
83 84 85
    state1.marker = 'original';

    await tester.pumpWidget(
86
      const MaterialApp(
87
        debugShowMaterialGrid: true,
88
        home: StateMarker(),
89
      ),
90 91
    );

92
    final StateMarkerState state2 = tester.state(find.byType(StateMarker));
93 94 95
    expect(state1, equals(state2));
    expect(state2.marker, equals('original'));
  });
96

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

    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));
138
    expect(buildCounter, 1);
139
    expect(find.text('Y'), findsOneWidget);
140 141
  });

142 143 144
  testWidgets('Do rebuild the home page if it changes', (WidgetTester tester) async {
    int buildCounter = 0;
    await tester.pumpWidget(
145 146
      MaterialApp(
        home: Builder(
147 148 149
          builder: (BuildContext context) {
            ++buildCounter;
            return const Text('A');
150
          },
151 152 153 154 155 156
        ),
      ),
    );
    expect(buildCounter, 1);
    expect(find.text('A'), findsOneWidget);
    await tester.pumpWidget(
157 158
      MaterialApp(
        home: Builder(
159 160 161
          builder: (BuildContext context) {
            ++buildCounter;
            return const Text('B');
162
          },
163 164 165 166 167 168 169 170 171
        ),
      ),
    );
    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;
172
    final Widget home = Builder(
173 174 175
      builder: (BuildContext context) {
        ++buildCounter;
        return const Placeholder();
176
      },
177 178
    );
    await tester.pumpWidget(
179
      MaterialApp(
180 181 182 183 184
        home: home,
      ),
    );
    expect(buildCounter, 1);
    await tester.pumpWidget(
185
      MaterialApp(
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
        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(
201
      MaterialApp(
202 203 204 205 206
        routes: routes,
      ),
    );
    expect(buildCounter, 1);
    await tester.pumpWidget(
207
      MaterialApp(
208 209 210 211 212 213
        routes: routes,
      ),
    );
    expect(buildCounter, 2);
  });

214
  testWidgets('Cannot pop the initial route', (WidgetTester tester) async {
215
    await tester.pumpWidget(const MaterialApp(home: Text('Home')));
216 217 218

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

219 220
    final NavigatorState navigator = tester.state(find.byType(Navigator));
    final bool result = await navigator.maybePop();
221 222 223 224 225

    expect(result, isFalse);

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

  testWidgets('Default initialRoute', (WidgetTester tester) async {
228
    await tester.pumpWidget(MaterialApp(routes: <String, WidgetBuilder>{
229 230 231 232 233 234
      '/': (BuildContext context) => const Text('route "/"'),
    }));

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

235
  testWidgets('One-step initial route', (WidgetTester tester) async {
236
    await tester.pumpWidget(
237
      MaterialApp(
238 239
        initialRoute: '/a',
        routes: <String, WidgetBuilder>{
240
          '/': (BuildContext context) => const Text('route "/"'),
241
          '/a': (BuildContext context) => const Text('route "/a"'),
242 243
          '/a/b': (BuildContext context) => const Text('route "/a/b"'),
          '/b': (BuildContext context) => const Text('route "/b"'),
244
        },
245
      ),
246 247
    );

248
    expect(find.text('route "/"', skipOffstage: false), findsOneWidget);
249
    expect(find.text('route "/a"'), findsOneWidget);
250 251
    expect(find.text('route "/a/b"', skipOffstage: false), findsNothing);
    expect(find.text('route "/b"', skipOffstage: false), findsNothing);
252 253
  });

254
  testWidgets('Return value from pop is correct', (WidgetTester tester) async {
255
    late Future<Object?> result;
256
    await tester.pumpWidget(
257 258
        MaterialApp(
          home: Builder(
259 260 261 262 263 264 265 266 267 268
            builder: (BuildContext context) {
              return Material(
                child: ElevatedButton(
                    child: const Text('X'),
                    onPressed: () async {
                      result = Navigator.of(context).pushNamed<Object?>('/a');
                    },
                ),
              );
            },
269 270 271
          ),
          routes: <String, WidgetBuilder>{
            '/a': (BuildContext context) {
272
              return Material(
273
                child: ElevatedButton(
274 275
                  child: const Text('Y'),
                  onPressed: () {
276
                    Navigator.of(context).pop('all done');
277 278 279
                  },
                ),
              );
280
            },
281
          },
282
        ),
283 284 285 286 287 288 289 290 291 292 293
    );
    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'));
  });

294
  testWidgets('Two-step initial route', (WidgetTester tester) async {
295 296 297
    final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{
      '/': (BuildContext context) => const Text('route "/"'),
      '/a': (BuildContext context) => const Text('route "/a"'),
298
      '/a/b': (BuildContext context) => const Text('route "/a/b"'),
299 300 301 302
      '/b': (BuildContext context) => const Text('route "/b"'),
    };

    await tester.pumpWidget(
303
      MaterialApp(
304
        initialRoute: '/a/b',
305
        routes: routes,
306
      ),
307
    );
308 309
    expect(find.text('route "/"', skipOffstage: false), findsOneWidget);
    expect(find.text('route "/a"', skipOffstage: false), findsOneWidget);
310
    expect(find.text('route "/a/b"'), findsOneWidget);
311
    expect(find.text('route "/b"', skipOffstage: false), findsNothing);
312 313 314 315 316 317 318 319 320 321 322
  });

  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(
323
      MaterialApp(
324 325
        initialRoute: '/a/b/c',
        routes: routes,
326
      ),
327 328
    );
    final dynamic exception = tester.takeException();
Dan Field's avatar
Dan Field committed
329
    expect(exception, isA<String>());
330 331 332 333 334 335 336
    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);
    }
337 338 339 340 341 342 343 344 345 346
  });

  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(
347
      MaterialApp(
348 349
        initialRoute: '/a',
        routes: routes,
350
      ),
351
    );
352
    expect(find.text('route "/"', skipOffstage: false), findsOneWidget);
353
    expect(find.text('route "/a"'), findsOneWidget);
354
    expect(find.text('route "/b"', skipOffstage: false), findsNothing);
355

356
    // changing initialRoute has no effect
357
    await tester.pumpWidget(
358
      MaterialApp(
359 360
        initialRoute: '/b',
        routes: routes,
361
      ),
362
    );
363
    expect(find.text('route "/"', skipOffstage: false), findsOneWidget);
364
    expect(find.text('route "/a"'), findsOneWidget);
365
    expect(find.text('route "/b"', skipOffstage: false), findsNothing);
366

367
    // removing it has no effect
368
    await tester.pumpWidget(MaterialApp(routes: routes));
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 374 375 376

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

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

396 397 398 399
  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(
400
        builder: (BuildContext context, Widget? child) {
401 402 403 404 405 406
          return const SizedBox();
        },
      ),
    );
  });

407
  testWidgets("WidgetsApp doesn't rebuild routes when MediaQuery updates", (WidgetTester tester) async {
408
    // Regression test for https://github.com/flutter/flutter/issues/37878
409 410 411
    addTearDown(tester.platformDispatcher.clearAllTestValues);
    addTearDown(tester.view.reset);

412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434
    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
435
    tester.view.physicalSize = const Size(42, 42);
436 437 438 439 440 441 442

    await tester.pump();

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

    // didChangeTextScaleFactor
443
    tester.platformDispatcher.textScaleFactorTestValue = 42;
444 445 446 447 448 449 450

    await tester.pump();

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

    // didChangePlatformBrightness
451
    tester.platformDispatcher.platformBrightnessTestValue = Brightness.dark;
452 453 454 455 456 457 458

    await tester.pump();

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

    // didChangeAccessibilityFeatures
459
    tester.platformDispatcher.accessibilityFeaturesTestValue = FakeAccessibilityFeatures.allOn;
460 461 462 463 464 465 466

    await tester.pump();

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

467
  testWidgets('Can get text scale from media query', (WidgetTester tester) async {
468
    TextScaler? textScaler;
469 470
    await tester.pumpWidget(MaterialApp(
      home: Builder(builder:(BuildContext context) {
471
        textScaler = MediaQuery.textScalerOf(context);
472
        return Container();
473 474
      }),
    ));
475
    expect(textScaler, TextScaler.noScaling);
476
  });
477 478

  testWidgets('MaterialApp.navigatorKey', (WidgetTester tester) async {
479 480
    final GlobalKey<NavigatorState> key = GlobalKey<NavigatorState>();
    await tester.pumpWidget(MaterialApp(
481 482 483 484
      navigatorKey: key,
      color: const Color(0xFF112233),
      home: const Placeholder(),
    ));
Dan Field's avatar
Dan Field committed
485
    expect(key.currentState, isA<NavigatorState>());
486 487 488
    await tester.pumpWidget(const MaterialApp(
      color: Color(0xFF112233),
      home: Placeholder(),
489 490
    ));
    expect(key.currentState, isNull);
491
    await tester.pumpWidget(MaterialApp(
492 493 494 495
      navigatorKey: key,
      color: const Color(0xFF112233),
      home: const Placeholder(),
    ));
Dan Field's avatar
Dan Field committed
496
    expect(key.currentState, isA<NavigatorState>());
497
  });
498 499 500 501 502 503 504 505

  testWidgets('Has default material and cupertino localizations', (WidgetTester tester) async {
    await tester.pumpWidget(
      MaterialApp(
        home: Builder(
          builder: (BuildContext context) {
            return Column(
              children: <Widget>[
506 507
                Text(MaterialLocalizations.of(context).selectAllButtonLabel),
                Text(CupertinoLocalizations.of(context).selectAllButtonLabel),
508 509 510 511 512 513 514 515
              ],
            );
          },
        ),
      ),
    );

    // Default US "select all" text.
516
    expect(find.text('Select all'), findsOneWidget);
517 518 519
    // Default Cupertino US "select all" text.
    expect(find.text('Select All'), findsOneWidget);
  });
520

521
  testWidgets('MaterialApp uses regular theme when themeMode is light', (WidgetTester tester) async {
522 523 524 525
    addTearDown(tester.platformDispatcher.clearAllTestValues);

    // Mock the test to explicitly report a light platformBrightness.
    tester.platformDispatcher.platformBrightnessTestValue = Brightness.light;
526

527
    late ThemeData appliedTheme;
528 529 530
    await tester.pumpWidget(
      MaterialApp(
        theme: ThemeData(
531
          brightness: Brightness.light,
532 533 534 535 536 537 538
        ),
        darkTheme: ThemeData(
          brightness: Brightness.dark,
        ),
        themeMode: ThemeMode.light,
        home: Builder(
          builder: (BuildContext context) {
539
            appliedTheme = Theme.of(context);
540 541 542 543 544 545 546
            return const SizedBox();
          },
        ),
      ),
    );
    expect(appliedTheme.brightness, Brightness.light);

547 548
    // Mock the test to explicitly report a dark platformBrightness.
    tester.platformDispatcher.platformBrightnessTestValue = Brightness.dark;
549 550 551
    await tester.pumpWidget(
      MaterialApp(
        theme: ThemeData(
552
          brightness: Brightness.light,
553 554 555 556 557 558 559
        ),
        darkTheme: ThemeData(
          brightness: Brightness.dark,
        ),
        themeMode: ThemeMode.light,
        home: Builder(
          builder: (BuildContext context) {
560
            appliedTheme = Theme.of(context);
561 562 563 564 565 566 567 568 569
            return const SizedBox();
          },
        ),
      ),
    );
    expect(appliedTheme.brightness, Brightness.light);
  });

  testWidgets('MaterialApp uses darkTheme when themeMode is dark', (WidgetTester tester) async {
570 571 572 573
    addTearDown(tester.platformDispatcher.clearAllTestValues);

    // Mock the test to explicitly report a light platformBrightness.
    tester.platformDispatcher.platformBrightnessTestValue = Brightness.light;
574

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

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

  testWidgets('MaterialApp uses regular theme when themeMode is system and platformBrightness is light', (WidgetTester tester) async {
618 619 620 621
    addTearDown(tester.platformDispatcher.clearAllTestValues);

    // Mock the test to explicitly report a light platformBrightness.
    tester.platformDispatcher.platformBrightnessTestValue = Brightness.light;
622

623
    late ThemeData appliedTheme;
624 625 626 627

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

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

645
  testWidgets('MaterialApp uses darkTheme when themeMode is system and platformBrightness is dark', (WidgetTester tester) async {
646 647 648 649
    addTearDown(tester.platformDispatcher.clearAllTestValues);

    // Mock the test to explicitly report a dark platformBrightness.
    tester.platformDispatcher.platformBrightnessTestValue = Brightness.dark;
650

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

671
  testWidgets('MaterialApp uses light theme when platformBrightness is dark but no dark theme is provided', (WidgetTester tester) async {
672 673 674 675
    addTearDown(tester.platformDispatcher.clearAllTestValues);

    // Mock the test to explicitly report a dark platformBrightness.
    tester.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
            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 {
697 698 699 700
    addTearDown(tester.platformDispatcher.clearAllTestValues);

    // Mock the test to explicitly report a dark platformBrightness.
    tester.platformDispatcher.platformBrightnessTestValue = Brightness.dark;
701

702
    late ThemeData appliedTheme;
703 704 705 706 707

    await tester.pumpWidget(
      MaterialApp(
        home: Builder(
          builder: (BuildContext context) {
708
            appliedTheme = Theme.of(context);
709 710 711 712 713 714 715 716 717 718
            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 {
719 720 721 722
    addTearDown(tester.platformDispatcher.clearAllTestValues);

    // Mock the test to explicitly report a dark platformBrightness.
    tester.platformDispatcher.platformBrightnessTestValue = Brightness.light;
723

724
    late ThemeData appliedTheme;
725 726 727 728 729 730 731 732

    await tester.pumpWidget(
      MaterialApp(
        darkTheme: ThemeData(
          brightness: Brightness.dark,
        ),
        home: Builder(
          builder: (BuildContext context) {
733
            appliedTheme = Theme.of(context);
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 {
744 745 746 747
    addTearDown(tester.platformDispatcher.clearAllTestValues);

    // Mock the test to explicitly report a dark platformBrightness.
    tester.platformDispatcher.platformBrightnessTestValue = Brightness.dark;
748

749
    late ThemeData appliedTheme;
750 751 752 753

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

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

771
  testWidgets('MaterialApp uses high contrast theme when appropriate', (WidgetTester tester) async {
772 773 774 775
    addTearDown(tester.platformDispatcher.clearAllTestValues);

    tester.platformDispatcher.platformBrightnessTestValue = Brightness.light;
    tester.platformDispatcher.accessibilityFeaturesTestValue = FakeAccessibilityFeatures.allOn;
776

777
    late ThemeData appliedTheme;
778 779 780 781 782 783 784 785 786 787 788

    await tester.pumpWidget(
      MaterialApp(
        theme: ThemeData(
          primaryColor: Colors.lightBlue,
        ),
        highContrastTheme: ThemeData(
          primaryColor: Colors.blue,
        ),
        home: Builder(
          builder: (BuildContext context) {
789
            appliedTheme = Theme.of(context);
790 791 792 793 794 795 796 797 798 799
            return const SizedBox();
          },
        ),
      ),
    );

    expect(appliedTheme.primaryColor, Colors.blue);
  });

  testWidgets('MaterialApp uses high contrast dark theme when appropriate', (WidgetTester tester) async {
800 801 802 803
    addTearDown(tester.platformDispatcher.clearAllTestValues);

    tester.platformDispatcher.platformBrightnessTestValue = Brightness.dark;
    tester.platformDispatcher.accessibilityFeaturesTestValue = FakeAccessibilityFeatures.allOn;
804

805
    late ThemeData appliedTheme;
806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822

    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) {
823
            appliedTheme = Theme.of(context);
824 825 826 827 828 829 830 831 832
            return const SizedBox();
          },
        ),
      ),
    );

    expect(appliedTheme.primaryColor, Colors.green);
  });

833
  testWidgets('MaterialApp uses dark theme when no high contrast dark theme is provided', (WidgetTester tester) async {
834 835 836 837
    addTearDown(tester.platformDispatcher.clearAllTestValues);

    tester.platformDispatcher.platformBrightnessTestValue = Brightness.dark;
    tester.platformDispatcher.accessibilityFeaturesTestValue = FakeAccessibilityFeatures.allOn;
838

839
    late ThemeData appliedTheme;
840 841 842 843 844 845 846 847 848 849 850

    await tester.pumpWidget(
      MaterialApp(
        theme: ThemeData(
          primaryColor: Colors.lightBlue,
        ),
        darkTheme: ThemeData(
          primaryColor: Colors.lightGreen,
        ),
        home: Builder(
          builder: (BuildContext context) {
851
            appliedTheme = Theme.of(context);
852 853 854 855 856 857 858 859 860
            return const SizedBox();
          },
        ),
      ),
    );

    expect(appliedTheme.primaryColor, Colors.lightGreen);
  });

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 891 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 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942
  testWidgets('MaterialApp animates theme changes', (WidgetTester tester) async {
    final ThemeData lightTheme = ThemeData.light();
    final ThemeData darkTheme = ThemeData.dark();
    await tester.pumpWidget(
      MaterialApp(
        theme: lightTheme,
        darkTheme: darkTheme,
        themeMode: ThemeMode.light,
        home: Builder(
          builder: (BuildContext context) {
            return const Scaffold();
          },
        ),
      ),
    );
    expect(tester.widget<Material>(find.byType(Material)).color, lightTheme.scaffoldBackgroundColor);

    // Change to dark theme
    await tester.pumpWidget(
      MaterialApp(
        theme: ThemeData.light(),
        darkTheme: ThemeData.dark(),
        themeMode: ThemeMode.dark,
        home: Builder(
          builder: (BuildContext context) {
            return const Scaffold();
          },
        ),
      ),
    );

    // Wait half kThemeAnimationDuration = 200ms.
    await tester.pump(const Duration(milliseconds: 100));

    // Default curve is linear so background should be half way between
    // the two colors.
    final Color halfBGColor = Color.lerp(lightTheme.scaffoldBackgroundColor, darkTheme.scaffoldBackgroundColor, 0.5)!;
    expect(tester.widget<Material>(find.byType(Material)).color, halfBGColor);
  });

  testWidgets('MaterialApp theme animation can be turned off', (WidgetTester tester) async {
    final ThemeData lightTheme = ThemeData.light();
    final ThemeData darkTheme = ThemeData.dark();
    int scaffoldRebuilds = 0;

    final Widget scaffold = Builder(
      builder: (BuildContext context) {
        scaffoldRebuilds++;
        // Use Theme.of() to ensure we are building when the theme changes.
        return Scaffold(backgroundColor: Theme.of(context).scaffoldBackgroundColor);
      },
    );

    await tester.pumpWidget(
      MaterialApp(
        theme: lightTheme,
        darkTheme: darkTheme,
        themeMode: ThemeMode.light,
        themeAnimationDuration: Duration.zero,
        home: scaffold,
      ),
    );
    expect(tester.widget<Material>(find.byType(Material)).color, lightTheme.scaffoldBackgroundColor);
    expect(scaffoldRebuilds, 1);

    // Change to dark theme
    await tester.pumpWidget(
      MaterialApp(
        theme: ThemeData.light(),
        darkTheme: ThemeData.dark(),
        themeMode: ThemeMode.dark,
        themeAnimationDuration: Duration.zero,
        home: scaffold,
      ),
    );

    // Wait for any animation to finish.
    await tester.pumpAndSettle();
    expect(tester.widget<Material>(find.byType(Material)).color, darkTheme.scaffoldBackgroundColor);
    expect(scaffoldRebuilds, 2);
  });

943 944 945 946 947
  testWidgets('MaterialApp switches themes when the platformBrightness changes.', (WidgetTester tester) async {
    addTearDown(tester.platformDispatcher.clearAllTestValues);

    // Mock the test to explicitly report a light platformBrightness.
    tester.platformDispatcher.platformBrightnessTestValue = Brightness.light;
948

949 950
    ThemeData? themeBeforeBrightnessChange;
    ThemeData? themeAfterBrightnessChange;
951 952 953 954

    await tester.pumpWidget(
      MaterialApp(
        theme: ThemeData(
955
          brightness: Brightness.light,
956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974
        ),
        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.
975
    tester.platformDispatcher.platformBrightnessTestValue = Brightness.dark;
976 977
    await tester.pumpAndSettle();

978 979
    expect(themeBeforeBrightnessChange!.brightness, Brightness.light);
    expect(themeAfterBrightnessChange!.brightness, Brightness.dark);
980
  });
981

982 983 984 985 986 987 988 989 990 991 992 993 994 995 996
  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(
997
      useMaterial3: false,
998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013
      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));
  });

1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025
  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,
1026 1027
                Animation<double> secondaryAnimation,
              ) {
1028
                return const Text('non-regular page one');
1029
              },
1030 1031 1032 1033 1034
            ),
            PageRouteBuilder<void>(
              pageBuilder: (
                BuildContext context,
                Animation<double> animation,
1035 1036
                Animation<double> secondaryAnimation,
              ) {
1037
                return const Text('non-regular page two');
1038
              },
1039 1040 1041 1042 1043 1044 1045 1046
            ),
          ];
        },
        initialRoute: '/abc',
        routes: <String, WidgetBuilder>{
          '/': (BuildContext context) => const Text('regular page one'),
          '/abc': (BuildContext context) => const Text('regular page two'),
        },
1047
      ),
1048 1049 1050 1051 1052
    );
    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);
1053
    navigatorKey.currentState!.pop();
1054 1055 1056 1057 1058 1059
    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);
  });
1060 1061 1062

  testWidgets('MaterialApp does create HeroController with the MaterialRectArcTween', (WidgetTester tester) async {
    final HeroController controller = MaterialApp.createMaterialHeroController();
1063
    final Tween<Rect?> tween = controller.createRectTween!(
1064
      const Rect.fromLTRB(0.0, 0.0, 10.0, 10.0),
1065
      const Rect.fromLTRB(0.0, 0.0, 20.0, 20.0),
1066 1067 1068
    );
    expect(tween, isA<MaterialRectArcTween>());
  });
1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084

  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);
  });
1085 1086 1087

  testWidgets('MaterialApp.router works', (WidgetTester tester) async {
    final PlatformRouteInformationProvider provider = PlatformRouteInformationProvider(
1088 1089
      initialRouteInformation: RouteInformation(
        uri: Uri.parse('initial'),
1090 1091 1092 1093
      ),
    );
    final SimpleNavigatorRouterDelegate delegate = SimpleNavigatorRouterDelegate(
      builder: (BuildContext context, RouteInformation information) {
1094
        return Text(information.uri.toString());
1095 1096
      },
      onPopPage: (Route<void> route, void result, SimpleNavigatorRouterDelegate delegate) {
1097 1098
        delegate.routeInformation = RouteInformation(
          uri: Uri.parse('popped'),
1099 1100
        );
        return route.didPop(result);
1101
      },
1102 1103 1104 1105 1106 1107 1108 1109 1110 1111
    );
    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'));
1112
    await tester.binding.defaultBinaryMessenger.handlePlatformMessage('flutter/navigation', message, (_) { });
1113 1114 1115 1116 1117 1118 1119
    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) {
1120
        return Text(information.uri.toString());
1121 1122
      },
      onPopPage: (Route<void> route, void result, SimpleNavigatorRouterDelegate delegate) {
1123 1124
        delegate.routeInformation = RouteInformation(
          uri: Uri.parse('popped'),
1125 1126 1127 1128
        );
        return route.didPop(result);
      },
    );
1129
    delegate.routeInformation = RouteInformation(uri: Uri.parse('initial'));
1130 1131 1132 1133 1134 1135 1136
    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'));
1137
    await tester.binding.defaultBinaryMessenger.handlePlatformMessage('flutter/navigation', message, (_) { });
1138 1139 1140 1141 1142 1143 1144
    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) {
1145
        return Text(information.uri.toString());
1146 1147
      },
      onPopPage: (Route<void> route, void result, SimpleNavigatorRouterDelegate delegate) {
1148 1149
        delegate.routeInformation = RouteInformation(
          uri: Uri.parse('popped'),
1150 1151 1152 1153
        );
        return route.didPop(result);
      },
    );
1154
    delegate.routeInformation = RouteInformation(uri: Uri.parse('initial'));
1155
    final PlatformRouteInformationProvider provider = PlatformRouteInformationProvider(
1156 1157
      initialRouteInformation: RouteInformation(
        uri: Uri.parse('initial'),
1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169
      ),
    );
    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) {
1170
        return Text(information.uri.toString());
1171 1172
      },
      onPopPage: (Route<void> route, void result, SimpleNavigatorRouterDelegate delegate) {
1173 1174
        delegate.routeInformation = RouteInformation(
          uri: Uri.parse('popped'),
1175 1176 1177 1178
        );
        return route.didPop(result);
      },
    );
1179
    delegate.routeInformation = RouteInformation(uri: Uri.parse('initial'));
1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190
    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(
1191 1192
          initialRouteInformation: RouteInformation(
            uri: Uri.parse('initial'),
1193 1194 1195 1196 1197
          ),
        ),
        routeInformationParser: SimpleRouteInformationParser(),
        routerDelegate: SimpleNavigatorRouterDelegate(
          builder: (BuildContext context, RouteInformation information) {
1198
            return Text(information.uri.toString());
1199 1200
          },
          onPopPage: (Route<void> route, void result, SimpleNavigatorRouterDelegate delegate) {
1201 1202
            delegate.routeInformation = RouteInformation(
              uri: Uri.parse('popped'),
1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215
            );
            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'));
1216
    await tester.binding.defaultBinaryMessenger.handlePlatformMessage('flutter/navigation', message, (_) { });
1217 1218 1219
    await tester.pumpAndSettle();
    expect(find.text('popped'), findsOneWidget);
  });
1220 1221

  testWidgets('MaterialApp.builder can build app without a Navigator', (WidgetTester tester) async {
1222
    Widget? builderChild;
1223
    await tester.pumpWidget(MaterialApp(
1224
      builder: (BuildContext context, Widget? child) {
1225 1226 1227 1228 1229 1230
        builderChild = child;
        return Container();
      },
    ));
    expect(builderChild, isNull);
  });
1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250

  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(
1251
        scrollBehavior: const MockScrollBehavior(),
1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263
        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);
  });
1264

1265 1266
  testWidgets('ScrollBehavior default android overscroll indicator', (WidgetTester tester) async {
    await tester.pumpWidget(MaterialApp(
1267
      theme: ThemeData(useMaterial3: false),
1268 1269 1270 1271 1272 1273 1274
      scrollBehavior: const MaterialScrollBehavior(),
      home: ListView(
        children: const <Widget>[
          SizedBox(
            height: 1000.0,
            width: 1000.0,
            child: Text('Test'),
1275 1276 1277
          ),
        ],
      ),
1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292
    ));

    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'),
1293 1294 1295
          ),
        ],
      ),
1296 1297 1298 1299 1300 1301
    ));

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

1302 1303 1304
  testWidgets('ScrollBehavior stretch android overscroll indicator via useMaterial3 flag', (WidgetTester tester) async {
    await tester.pumpWidget(MaterialApp(
      theme: ThemeData(useMaterial3: true),
1305 1306 1307 1308 1309 1310 1311 1312 1313
      home: ListView(
        children: const <Widget>[
          SizedBox(
            height: 1000.0,
            width: 1000.0,
            child: Text('Test'),
          ),
        ],
      ),
1314 1315 1316 1317 1318 1319
    ));

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

1320 1321 1322 1323 1324 1325 1326 1327 1328 1329
  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'),
1330 1331 1332
          ),
        ],
      ),
1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349
    ));

    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'),
1350 1351 1352
          ),
        ],
      ),
1353 1354 1355 1356 1357
    ));

    expect(find.byType(StretchingOverscrollIndicator), findsOneWidget);
    expect(find.byType(GlowingOverscrollIndicator), findsNothing);
  }, variant: TargetPlatformVariant.only(TargetPlatform.android));
1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434

  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));
1435

1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454
  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);
  });
1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479

  testWidgets('Assert in buildScrollbar that controller != null when using it (vertical)', (WidgetTester tester) async {
    const ScrollBehavior defaultBehavior = MaterialScrollBehavior();
    late BuildContext capturedContext;

    await tester.pumpWidget(MaterialApp(
      home: ScrollConfiguration(
        // Avoid the default ones here.
        behavior: const MaterialScrollBehavior().copyWith(scrollbars: false),
        child: SingleChildScrollView(
          child: Builder(
            builder: (BuildContext context) {
              capturedContext = context;
              return Container(height: 1000.0);
            },
          ),
        ),
      ),
    ));

    const ScrollableDetails details = ScrollableDetails(
      direction: AxisDirection.down,
    );
    final Widget child = Container();

1480
    switch (defaultTargetPlatform) {
1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525
      case TargetPlatform.android:
      case TargetPlatform.fuchsia:
      case TargetPlatform.iOS:
        // Does not throw if we aren't using it.
        defaultBehavior.buildScrollbar(capturedContext, child, details);
      case TargetPlatform.linux:
      case TargetPlatform.macOS:
      case TargetPlatform.windows:
        expect(
          () {
            defaultBehavior.buildScrollbar(capturedContext, child, details);
          },
          throwsA(
            isA<AssertionError>().having((AssertionError error) => error.toString(),
              'description', contains('details.controller != null')),
          ),
        );
    }
  }, variant: TargetPlatformVariant.all());

  testWidgets('Assert in buildScrollbar that controller != null when using it (horizontal)', (WidgetTester tester) async {
    const ScrollBehavior defaultBehavior = MaterialScrollBehavior();
    late BuildContext capturedContext;

    await tester.pumpWidget(MaterialApp(
      home: ScrollConfiguration(
        // Avoid the default ones here.
        behavior: const MaterialScrollBehavior().copyWith(scrollbars: false),
        child: SingleChildScrollView(
          scrollDirection: Axis.horizontal,
          child: Builder(
            builder: (BuildContext context) {
              capturedContext = context;
              return Container(height: 1000.0);
            },
          ),
        ),
      ),
    ));

    const ScrollableDetails details = ScrollableDetails(
      direction: AxisDirection.left,
    );
    final Widget child = Container();

1526
    switch (defaultTargetPlatform) {
1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537
      case TargetPlatform.android:
      case TargetPlatform.fuchsia:
      case TargetPlatform.iOS:
      case TargetPlatform.linux:
      case TargetPlatform.macOS:
      case TargetPlatform.windows:
        // Does not throw if we aren't using it.
        // Horizontal axis gets no scrollbars for all platforms.
        defaultBehavior.buildScrollbar(capturedContext, child, details);
    }
  }, variant: TargetPlatformVariant.all());
1538 1539 1540
}

class MockScrollBehavior extends ScrollBehavior {
1541 1542
  const MockScrollBehavior();

1543 1544
  @override
  ScrollPhysics getScrollPhysics(BuildContext context) => const NeverScrollableScrollPhysics();
1545
}
1546

1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565
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({
1566 1567
    required this.builder,
    required this.onPopPage,
1568 1569 1570 1571 1572 1573
  });

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

  RouteInformation get routeInformation => _routeInformation;
1574
  late RouteInformation _routeInformation;
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
  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.
1601 1602
        const MaterialPage<void>(
          child: Text('base'),
1603 1604
        ),
        MaterialPage<void>(
1605
          key: ValueKey<String>(routeInformation.uri.toString()),
1606
          child: builder(context, routeInformation),
1607
        ),
1608 1609 1610 1611
      ],
    );
  }
}