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

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

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

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

19
class StateMarker extends StatefulWidget {
20
  const StateMarker({ Key? key, this.child }) : super(key: key);
21

22
  final Widget? child;
23 24

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

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

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

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

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

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

62
    expect(focusNode.hasFocus, isTrue);
63
  });
64

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

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

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

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

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

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

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

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

    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));
142
    expect(buildCounter, 1);
143
    expect(find.text('Y'), findsOneWidget);
144 145
  });

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

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

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

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

    expect(result, isFalse);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462
  testWidgets("WidgetsApp don't rebuild routes when MediaQuery updates", (WidgetTester tester) async {
    // Regression test for https://github.com/flutter/flutter/issues/37878
    int routeBuildCount = 0;
    int dependentBuildCount = 0;

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

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

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

    await tester.pump();

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

    // didChangeTextScaleFactor
    tester.binding.window.textScaleFactorTestValue = 42;
    addTearDown(tester.binding.window.clearTextScaleFactorTestValue);

    await tester.pump();

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

    // didChangePlatformBrightness
    tester.binding.window.platformBrightnessTestValue = Brightness.dark;
    addTearDown(tester.binding.window.clearPlatformBrightnessTestValue);

    await tester.pump();

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

    // didChangeAccessibilityFeatures
463
    tester.binding.window.accessibilityFeaturesTestValue = FakeAccessibilityFeatures.allOn;
464 465 466 467 468 469 470 471
    addTearDown(tester.binding.window.clearAccessibilityFeaturesTestValue);

    await tester.pump();

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

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

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

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

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

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

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

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

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

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

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

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

624
    late ThemeData appliedTheme;
625 626 627 628

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

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

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

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

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

675
    late ThemeData appliedTheme;
676 677 678 679

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

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

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

699
    late ThemeData appliedTheme;
700 701 702 703 704

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

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

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

720
    late ThemeData appliedTheme;
721 722 723 724 725 726 727 728

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

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

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

744
    late ThemeData appliedTheme;
745 746 747 748

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

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

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

770
    late ThemeData appliedTheme;
771 772 773 774 775 776 777 778 779 780 781

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

    expect(appliedTheme.primaryColor, Colors.blue);
790
    tester.binding.window.clearAccessibilityFeaturesTestValue();
791 792 793 794
  });

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

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

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

    expect(appliedTheme.primaryColor, Colors.green);
823
    tester.binding.window.clearAccessibilityFeaturesTestValue();
824 825
  });

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

830
    late ThemeData appliedTheme;
831 832 833 834 835 836 837 838 839 840 841

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

    expect(appliedTheme.primaryColor, Colors.lightGreen);
850 851
    tester.binding.window.clearAccessibilityFeaturesTestValue();
    tester.binding.window.clearPlatformBrightnessTestValue();
852 853
  });

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

859 860
    ThemeData? themeBeforeBrightnessChange;
    ThemeData? themeAfterBrightnessChange;
861 862 863 864

    await tester.pumpWidget(
      MaterialApp(
        theme: ThemeData(
865
          brightness: Brightness.light,
866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887
        ),
        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.
    binding.window.platformBrightnessTestValue = Brightness.dark;
    await tester.pumpAndSettle();

888 889
    expect(themeBeforeBrightnessChange!.brightness, Brightness.light);
    expect(themeAfterBrightnessChange!.brightness, Brightness.dark);
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
  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));
  });

923 924 925 926 927 928 929 930 931 932 933 934
  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,
935 936
                Animation<double> secondaryAnimation,
              ) {
937
                return const Text('non-regular page one');
938
              },
939 940 941 942 943
            ),
            PageRouteBuilder<void>(
              pageBuilder: (
                BuildContext context,
                Animation<double> animation,
944 945
                Animation<double> secondaryAnimation,
              ) {
946
                return const Text('non-regular page two');
947
              },
948 949 950 951 952 953 954 955
            ),
          ];
        },
        initialRoute: '/abc',
        routes: <String, WidgetBuilder>{
          '/': (BuildContext context) => const Text('regular page one'),
          '/abc': (BuildContext context) => const Text('regular page two'),
        },
956
      ),
957 958 959 960 961
    );
    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);
962
    navigatorKey.currentState!.pop();
963 964 965 966 967 968
    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);
  });
969 970 971

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

  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);
  });
994 995 996 997 998 999 1000 1001 1002

  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) {
1003
        return Text(information.location!);
1004 1005 1006 1007 1008 1009
      },
      onPopPage: (Route<void> route, void result, SimpleNavigatorRouterDelegate delegate) {
        delegate.routeInformation = const RouteInformation(
          location: 'popped',
        );
        return route.didPop(result);
1010
      },
1011 1012 1013 1014 1015 1016 1017 1018 1019 1020
    );
    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'));
1021
    await ServicesBinding.instance!.defaultBinaryMessenger.handlePlatformMessage('flutter/navigation', message, (_) { });
1022 1023 1024
    await tester.pumpAndSettle();
    expect(find.text('popped'), findsOneWidget);
  });
1025 1026

  testWidgets('MaterialApp.builder can build app without a Navigator', (WidgetTester tester) async {
1027
    Widget? builderChild;
1028
    await tester.pumpWidget(MaterialApp(
1029
      builder: (BuildContext context, Widget? child) {
1030 1031 1032 1033 1034 1035
        builderChild = child;
        return Container();
      },
    ));
    expect(builderChild, isNull);
  });
1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055

  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(
1056
        scrollBehavior: const MockScrollBehavior(),
1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068
        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);
  });
1069

1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105
  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'),
          )
        ]
      )
    ));

    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'),
          )
        ]
      )
    ));

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

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
  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'),
          )
        ]
      )
    ));

    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'),
          )
        ]
      )
    ));

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

1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163
  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);
  });
1164 1165 1166
}

class MockScrollBehavior extends ScrollBehavior {
1167 1168
  const MockScrollBehavior();

1169 1170
  @override
  ScrollPhysics getScrollPhysics(BuildContext context) => const NeverScrollableScrollPhysics();
1171
}
1172

1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191
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({
1192 1193
    required this.builder,
    required this.onPopPage,
1194 1195 1196 1197 1198 1199
  });

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

  RouteInformation get routeInformation => _routeInformation;
1200
  late RouteInformation _routeInformation;
1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226
  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.
1227 1228
        const MaterialPage<void>(
          child: Text('base'),
1229 1230
        ),
        MaterialPage<void>(
1231
          key: ValueKey<String>(routeInformation.location!),
1232
          child: builder(context, routeInformation),
1233
        ),
1234 1235 1236 1237
      ],
    );
  }
}