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

5
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
import 'package:flutter_test/flutter_test.dart';
11
import 'package:leak_tracker_flutter_testing/leak_tracker_flutter_testing.dart';
12

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

16
  final Widget? child;
17 18

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

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

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

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

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

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

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

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

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

    expect(find.text('Home'), findsOneWidget);
72
    focusScopeNode.dispose();
73 74
  });

75
  testWidgetsWithLeakTracking('Can show grid without losing sync', (WidgetTester tester) async {
76
    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
  testWidgetsWithLeakTracking('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
  testWidgetsWithLeakTracking('Do rebuild the home page if it changes', (WidgetTester tester) async {
143 144
    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
        ),
      ),
    );
    expect(buildCounter, 2);
    expect(find.text('B'), findsOneWidget);
  });

170
  testWidgetsWithLeakTracking('Do not rebuild the home page if it does not actually change', (WidgetTester tester) async {
171
    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
        home: home,
      ),
    );
    expect(buildCounter, 1);
  });

192
  testWidgetsWithLeakTracking('Do rebuild pages that come from the routes table if the MaterialApp changes', (WidgetTester tester) async {
193 194 195 196 197 198 199 200
    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
  testWidgetsWithLeakTracking('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
  testWidgetsWithLeakTracking('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
  testWidgetsWithLeakTracking('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
  testWidgetsWithLeakTracking('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
  testWidgetsWithLeakTracking('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
  testWidgetsWithLeakTracking('Initial route with missing step', (WidgetTester tester) async {
315 316 317 318 319 320 321 322
    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
  testWidgetsWithLeakTracking('Make sure initialRoute is only used the first time', (WidgetTester tester) async {
340 341 342 343 344 345 346
    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
  testWidgetsWithLeakTracking('onGenerateRoute / onUnknownRoute', (WidgetTester tester) async {
375 376
    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
  testWidgetsWithLeakTracking('MaterialApp with builder and no route information works.', (WidgetTester tester) async {
397 398 399
    // 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
  testWidgetsWithLeakTracking("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
  testWidgetsWithLeakTracking('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
  testWidgetsWithLeakTracking('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
  testWidgetsWithLeakTracking('Has default material and cupertino localizations', (WidgetTester tester) async {
500 501 502 503 504 505
    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
  testWidgetsWithLeakTracking('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
            return const SizedBox();
          },
        ),
      ),
    );
    expect(appliedTheme.brightness, Brightness.light);
  });

569
  testWidgetsWithLeakTracking('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
            return const SizedBox();
          },
        ),
      ),
    );
    expect(appliedTheme.brightness, Brightness.dark);
  });

617
  testWidgetsWithLeakTracking('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
  testWidgetsWithLeakTracking('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
  testWidgetsWithLeakTracking('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
            return const SizedBox();
          },
        ),
      ),
    );

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

696
  testWidgetsWithLeakTracking('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
            return const SizedBox();
          },
        ),
      ),
    );

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

718
  testWidgetsWithLeakTracking('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
            return const SizedBox();
          },
        ),
      ),
    );

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

743
  testWidgetsWithLeakTracking('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
  testWidgetsWithLeakTracking('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
            return const SizedBox();
          },
        ),
      ),
    );

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

799
  testWidgetsWithLeakTracking('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
  testWidgetsWithLeakTracking('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
  testWidgetsWithLeakTracking('MaterialApp animates theme changes', (WidgetTester tester) async {
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
    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);
  });

901
  testWidgetsWithLeakTracking('MaterialApp theme animation can be turned off', (WidgetTester tester) async {
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
    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
  testWidgetsWithLeakTracking('MaterialApp switches themes when the platformBrightness changes.', (WidgetTester tester) async {
944 945 946 947
    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
  testWidgetsWithLeakTracking('Material2 - MaterialApp provides default overscroll color', (WidgetTester tester) async {
983 984 985 986 987 988 989 990 991 992 993 994 995 996
    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
  testWidgetsWithLeakTracking('MaterialApp can customize initial routes', (WidgetTester tester) async {
1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025
    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
  testWidgetsWithLeakTracking('MaterialApp does create HeroController with the MaterialRectArcTween', (WidgetTester tester) async {
1062
    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
  testWidgetsWithLeakTracking('MaterialApp.navigatorKey can be updated', (WidgetTester tester) async {
1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084
    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
  testWidgetsWithLeakTracking('MaterialApp.router works', (WidgetTester tester) async {
1087
    final PlatformRouteInformationProvider provider = PlatformRouteInformationProvider(
1088 1089
      initialRouteInformation: RouteInformation(
        uri: Uri.parse('initial'),
1090 1091
      ),
    );
1092
    addTearDown(provider.dispose);
1093 1094
    final SimpleNavigatorRouterDelegate delegate = SimpleNavigatorRouterDelegate(
      builder: (BuildContext context, RouteInformation information) {
1095
        return Text(information.uri.toString());
1096 1097
      },
      onPopPage: (Route<void> route, void result, SimpleNavigatorRouterDelegate delegate) {
1098 1099
        delegate.routeInformation = RouteInformation(
          uri: Uri.parse('popped'),
1100 1101
        );
        return route.didPop(result);
1102
      },
1103
    );
1104
    addTearDown(delegate.dispose);
1105 1106 1107 1108 1109 1110 1111 1112 1113
    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'));
1114
    await tester.binding.defaultBinaryMessenger.handlePlatformMessage('flutter/navigation', message, (_) { });
1115 1116
    await tester.pumpAndSettle();
    expect(find.text('popped'), findsOneWidget);
1117
  });
1118 1119

  testWidgetsWithLeakTracking('MaterialApp.router route information parser is optional', (WidgetTester tester) async {
1120 1121
    final SimpleNavigatorRouterDelegate delegate = SimpleNavigatorRouterDelegate(
      builder: (BuildContext context, RouteInformation information) {
1122
        return Text(information.uri.toString());
1123 1124
      },
      onPopPage: (Route<void> route, void result, SimpleNavigatorRouterDelegate delegate) {
1125 1126
        delegate.routeInformation = RouteInformation(
          uri: Uri.parse('popped'),
1127 1128 1129 1130
        );
        return route.didPop(result);
      },
    );
1131
    addTearDown(delegate.dispose);
1132
    delegate.routeInformation = RouteInformation(uri: Uri.parse('initial'));
1133 1134 1135 1136 1137 1138 1139
    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'));
1140
    await tester.binding.defaultBinaryMessenger.handlePlatformMessage('flutter/navigation', message, (_) { });
1141 1142
    await tester.pumpAndSettle();
    expect(find.text('popped'), findsOneWidget);
1143
  });
1144

1145
  testWidgetsWithLeakTracking('MaterialApp.router throw if route information provider is provided but no route information parser', (WidgetTester tester) async {
1146 1147
    final SimpleNavigatorRouterDelegate delegate = SimpleNavigatorRouterDelegate(
      builder: (BuildContext context, RouteInformation information) {
1148
        return Text(information.uri.toString());
1149 1150
      },
      onPopPage: (Route<void> route, void result, SimpleNavigatorRouterDelegate delegate) {
1151 1152
        delegate.routeInformation = RouteInformation(
          uri: Uri.parse('popped'),
1153 1154 1155 1156
        );
        return route.didPop(result);
      },
    );
1157
    addTearDown(delegate.dispose);
1158
    delegate.routeInformation = RouteInformation(uri: Uri.parse('initial'));
1159
    final PlatformRouteInformationProvider provider = PlatformRouteInformationProvider(
1160 1161
      initialRouteInformation: RouteInformation(
        uri: Uri.parse('initial'),
1162 1163 1164 1165 1166 1167 1168
      ),
    );
    await tester.pumpWidget(MaterialApp.router(
      routeInformationProvider: provider,
      routerDelegate: delegate,
    ));
    expect(tester.takeException(), isAssertionError);
1169
    provider.dispose();
1170 1171
  });

1172
  testWidgetsWithLeakTracking('MaterialApp.router throw if route configuration is provided along with other delegate', (WidgetTester tester) async {
1173 1174
    final SimpleNavigatorRouterDelegate delegate = SimpleNavigatorRouterDelegate(
      builder: (BuildContext context, RouteInformation information) {
1175
        return Text(information.uri.toString());
1176 1177
      },
      onPopPage: (Route<void> route, void result, SimpleNavigatorRouterDelegate delegate) {
1178 1179
        delegate.routeInformation = RouteInformation(
          uri: Uri.parse('popped'),
1180 1181 1182 1183
        );
        return route.didPop(result);
      },
    );
1184
    addTearDown(delegate.dispose);
1185
    delegate.routeInformation = RouteInformation(uri: Uri.parse('initial'));
1186 1187 1188 1189 1190 1191 1192 1193
    final RouterConfig<RouteInformation> routerConfig = RouterConfig<RouteInformation>(routerDelegate: delegate);
    await tester.pumpWidget(MaterialApp.router(
      routerDelegate: delegate,
      routerConfig: routerConfig,
    ));
    expect(tester.takeException(), isAssertionError);
  });

1194 1195 1196 1197 1198
  testWidgetsWithLeakTracking('MaterialApp.router router config works', (WidgetTester tester) async {
    late SimpleNavigatorRouterDelegate routerDelegate;
    addTearDown(() => routerDelegate.dispose());
    late PlatformRouteInformationProvider provider;
    addTearDown(() => provider.dispose());
1199
    final RouterConfig<RouteInformation> routerConfig = RouterConfig<RouteInformation>(
1200
        routeInformationProvider: provider = PlatformRouteInformationProvider(
1201 1202
          initialRouteInformation: RouteInformation(
            uri: Uri.parse('initial'),
1203 1204 1205
          ),
        ),
        routeInformationParser: SimpleRouteInformationParser(),
1206
        routerDelegate: routerDelegate = SimpleNavigatorRouterDelegate(
1207
          builder: (BuildContext context, RouteInformation information) {
1208
            return Text(information.uri.toString());
1209 1210
          },
          onPopPage: (Route<void> route, void result, SimpleNavigatorRouterDelegate delegate) {
1211 1212
            delegate.routeInformation = RouteInformation(
              uri: Uri.parse('popped'),
1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225
            );
            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'));
1226
    await tester.binding.defaultBinaryMessenger.handlePlatformMessage('flutter/navigation', message, (_) { });
1227 1228
    await tester.pumpAndSettle();
    expect(find.text('popped'), findsOneWidget);
1229
  });
1230

1231
  testWidgetsWithLeakTracking('MaterialApp.builder can build app without a Navigator', (WidgetTester tester) async {
1232
    Widget? builderChild;
1233
    await tester.pumpWidget(MaterialApp(
1234
      builder: (BuildContext context, Widget? child) {
1235 1236 1237 1238 1239 1240
        builderChild = child;
        return Container();
      },
    ));
    expect(builderChild, isNull);
  });
1241

1242
  testWidgetsWithLeakTracking('MaterialApp has correct default ScrollBehavior', (WidgetTester tester) async {
1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256
    late BuildContext capturedContext;
    await tester.pumpWidget(
      MaterialApp(
        home: Builder(
          builder: (BuildContext context) {
            capturedContext = context;
            return const Placeholder();
          },
        ),
      ),
    );
    expect(ScrollConfiguration.of(capturedContext).runtimeType, MaterialScrollBehavior);
  });

1257
  testWidgetsWithLeakTracking('A ScrollBehavior can be set for MaterialApp', (WidgetTester tester) async {
1258 1259 1260
    late BuildContext capturedContext;
    await tester.pumpWidget(
      MaterialApp(
1261
        scrollBehavior: const MockScrollBehavior(),
1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273
        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);
  });
1274

1275
  testWidgetsWithLeakTracking('Material2 - ScrollBehavior default android overscroll indicator', (WidgetTester tester) async {
1276
    await tester.pumpWidget(MaterialApp(
1277
      theme: ThemeData(useMaterial3: false),
1278 1279 1280 1281 1282 1283 1284
      scrollBehavior: const MaterialScrollBehavior(),
      home: ListView(
        children: const <Widget>[
          SizedBox(
            height: 1000.0,
            width: 1000.0,
            child: Text('Test'),
1285 1286 1287
          ),
        ],
      ),
1288 1289 1290 1291 1292 1293
    ));

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

1294
  testWidgetsWithLeakTracking('Material3 - ScrollBehavior default android overscroll indicator', (WidgetTester tester) async {
1295
    await tester.pumpWidget(MaterialApp(
1296 1297
      theme: ThemeData(useMaterial3: true),
      scrollBehavior: const MaterialScrollBehavior(),
1298 1299 1300 1301 1302 1303
      home: ListView(
        children: const <Widget>[
          SizedBox(
            height: 1000.0,
            width: 1000.0,
            child: Text('Test'),
1304 1305 1306
          ),
        ],
      ),
1307 1308 1309 1310 1311 1312
    ));

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

1313
  testWidgetsWithLeakTracking('MaterialScrollBehavior default stretch android overscroll indicator', (WidgetTester tester) async {
1314
    await tester.pumpWidget(MaterialApp(
1315 1316 1317 1318 1319 1320 1321 1322 1323
      home: ListView(
        children: const <Widget>[
          SizedBox(
            height: 1000.0,
            width: 1000.0,
            child: Text('Test'),
          ),
        ],
      ),
1324 1325 1326 1327 1328 1329
    ));

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

1330
  testWidgetsWithLeakTracking('Overscroll indicator can be set by theme', (WidgetTester tester) async {
1331
    await tester.pumpWidget(MaterialApp(
1332 1333
      // The current default is M3 and stretch overscroll, setting via the theme should override.
      theme: ThemeData().copyWith(useMaterial3: false),
1334 1335 1336 1337 1338 1339
      home: ListView(
        children: const <Widget>[
          SizedBox(
            height: 1000.0,
            width: 1000.0,
            child: Text('Test'),
1340 1341 1342
          ),
        ],
      ),
1343 1344
    ));

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

1349
  testWidgetsWithLeakTracking('Material3 - ListView clip behavior updates overscroll indicator clip behavior', (WidgetTester tester) async {
1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365
    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'),
                  );
                },
1366
              ),
1367 1368 1369 1370 1371 1372
            ),
            Opacity(
              opacity: 0.5,
              child: Container(
                color: const Color(0xD0FF0000),
                height: 100,
1373
              ),
1374 1375 1376 1377 1378
            ),
          ],
        ),
      );
    }
1379

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

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

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

1391 1392 1393 1394 1395 1396 1397 1398 1399
    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));
1400

1401 1402
    await gesture.up();
    await tester.pumpAndSettle();
1403

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

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

1411 1412 1413 1414 1415 1416 1417 1418 1419
    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));
1420

1421 1422
    await gesture.up();
    await tester.pumpAndSettle();
1423
  }, variant: TargetPlatformVariant.only(TargetPlatform.android));
1424

1425
  testWidgetsWithLeakTracking('When `useInheritedMediaQuery` is true an existing MediaQuery is used if one is available', (WidgetTester tester) async {
1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443
    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);
  });
1444

1445
  testWidgetsWithLeakTracking('Assert in buildScrollbar that controller != null when using it (vertical)', (WidgetTester tester) async {
1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468
    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();

1469
    switch (defaultTargetPlatform) {
1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489
      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());

1490
  testWidgetsWithLeakTracking('Assert in buildScrollbar that controller != null when using it (horizontal)', (WidgetTester tester) async {
1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514
    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();

1515
    switch (defaultTargetPlatform) {
1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526
      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());
1527 1528 1529
}

class MockScrollBehavior extends ScrollBehavior {
1530 1531
  const MockScrollBehavior();

1532 1533
  @override
  ScrollPhysics getScrollPhysics(BuildContext context) => const NeverScrollableScrollPhysics();
1534
}
1535

1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554
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({
1555 1556
    required this.builder,
    required this.onPopPage,
1557
  }) {
1558
    ChangeNotifier.maybeDispatchObjectCreation(this);
1559
  }
1560 1561 1562 1563 1564

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

  RouteInformation get routeInformation => _routeInformation;
1565
  late RouteInformation _routeInformation;
1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591
  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.
1592 1593
        const MaterialPage<void>(
          child: Text('base'),
1594 1595
        ),
        MaterialPage<void>(
1596
          key: ValueKey<String>(routeInformation.uri.toString()),
1597
          child: builder(context, routeInformation),
1598
        ),
1599 1600 1601 1602
      ],
    );
  }
}