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

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

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

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

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

24
  final Widget? child;
25 26

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    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));
145
    expect(buildCounter, 1);
146
    expect(find.text('Y'), findsOneWidget);
147 148
  });

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

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

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

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

    expect(result, isFalse);

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

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

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

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

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

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

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

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

  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(
330
      MaterialApp(
331 332
        initialRoute: '/a/b/c',
        routes: routes,
333
      ),
334 335
    );
    final dynamic exception = tester.takeException();
Dan Field's avatar
Dan Field committed
336
    expect(exception, isA<String>());
337 338 339 340 341 342 343
    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);
    }
344 345 346 347 348 349 350 351 352 353
  });

  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(
354
      MaterialApp(
355 356
        initialRoute: '/a',
        routes: routes,
357
      ),
358
    );
359
    expect(find.text('route "/"', skipOffstage: false), findsOneWidget);
360
    expect(find.text('route "/a"'), findsOneWidget);
361
    expect(find.text('route "/b"', skipOffstage: false), findsNothing);
362

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

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

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

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

403 404 405 406
  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(
407
        builder: (BuildContext context, Widget? child) {
408 409 410 411 412 413
          return const SizedBox();
        },
      ),
    );
  });

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

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

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

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

    await tester.pump();

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

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

    await tester.pump();

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

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

    await tester.pump();

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

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

    await tester.pump();

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

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

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

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

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

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

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

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

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

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

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

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

627
    late ThemeData appliedTheme;
628 629 630 631

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

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

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

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

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

678
    late ThemeData appliedTheme;
679 680 681 682

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

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

  testWidgets('MaterialApp uses fallback light theme when platformBrightness is dark but no theme is provided at all', (WidgetTester tester) async {
    // Mock the Window to explicitly report a dark platformBrightness.
    final TestWidgetsFlutterBinding binding = tester.binding;
700
    binding.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 719 720
            return const SizedBox();
          },
        ),
      ),
    );

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

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

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

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

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

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

747
    late ThemeData appliedTheme;
748 749 750 751

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

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

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

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

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

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

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

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

    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) {
818
            appliedTheme = Theme.of(context);
819 820 821 822 823 824 825
            return const SizedBox();
          },
        ),
      ),
    );

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

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

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

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

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

857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 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
  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);
  });

939 940 941
  testWidgets('MaterialApp switches themes when the Window platformBrightness changes.', (WidgetTester tester) async {
    // Mock the Window to explicitly report a light platformBrightness.
    final TestWidgetsFlutterBinding binding = tester.binding;
942
    binding.platformDispatcher.platformBrightnessTestValue = Brightness.light;
943

944 945
    ThemeData? themeBeforeBrightnessChange;
    ThemeData? themeAfterBrightnessChange;
946 947 948 949

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

973 974
    expect(themeBeforeBrightnessChange!.brightness, Brightness.light);
    expect(themeAfterBrightnessChange!.brightness, Brightness.dark);
975
  });
976

977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007
  testWidgets('MaterialApp provides default overscroll color', (WidgetTester tester) async {
    Future<void> slowDrag(WidgetTester tester, Offset start, Offset offset) async {
      final TestGesture gesture = await tester.startGesture(start);
      for (int index = 0; index < 10; index += 1) {
        await gesture.moveBy(offset);
        await tester.pump(const Duration(milliseconds: 20));
      }
      await gesture.up();
    }

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

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

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

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

  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);
  });
1079 1080 1081 1082 1083 1084 1085 1086 1087

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

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

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

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

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

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

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

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

  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(
1245
        scrollBehavior: const MockScrollBehavior(),
1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257
        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);
  });
1258

1259 1260 1261 1262 1263 1264 1265 1266 1267
  testWidgets('ScrollBehavior default android overscroll indicator', (WidgetTester tester) async {
    await tester.pumpWidget(MaterialApp(
      scrollBehavior: const MaterialScrollBehavior(),
      home: ListView(
        children: const <Widget>[
          SizedBox(
            height: 1000.0,
            width: 1000.0,
            child: Text('Test'),
1268 1269 1270
          ),
        ],
      ),
1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285
    ));

    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'),
1286 1287 1288
          ),
        ],
      ),
1289 1290 1291 1292 1293 1294
    ));

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

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

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

1313 1314 1315 1316 1317 1318 1319 1320 1321 1322
  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'),
1323 1324 1325
          ),
        ],
      ),
1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342
    ));

    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'),
1343 1344 1345
          ),
        ],
      ),
1346 1347 1348 1349 1350
    ));

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

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

1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447
  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);
  });
1448 1449 1450
}

class MockScrollBehavior extends ScrollBehavior {
1451 1452
  const MockScrollBehavior();

1453 1454
  @override
  ScrollPhysics getScrollPhysics(BuildContext context) => const NeverScrollableScrollPhysics();
1455
}
1456

1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475
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({
1476 1477
    required this.builder,
    required this.onPopPage,
1478 1479 1480 1481 1482 1483
  });

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

  RouteInformation get routeInformation => _routeInformation;
1484
  late RouteInformation _routeInformation;
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
  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.
1511 1512
        const MaterialPage<void>(
          child: Text('base'),
1513 1514
        ),
        MaterialPage<void>(
1515
          key: ValueKey<String>(routeInformation.location!),
1516
          child: builder(context, routeInformation),
1517
        ),
1518 1519 1520 1521
      ],
    );
  }
}