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

5
import 'package:flutter/foundation.dart';
6
import 'package:flutter/semantics.dart';
7
import 'package:flutter/services.dart';
8
import 'package:flutter_test/flutter_test.dart';
9
import 'package:flutter/cupertino.dart';
10
import 'package:flutter/material.dart';
11

12 13
import '../rendering/mock_canvas.dart';

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

17
  final Widget? child;
18 19

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    expect(result, isFalse);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

404 405 406 407 408 409 410 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 463 464
  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
    tester.binding.window.accessibilityFeaturesTestValue = MockAccessibilityFeature();
    addTearDown(tester.binding.window.clearAccessibilityFeaturesTestValue);

    await tester.pump();

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

465
  testWidgets('Can get text scale from media query', (WidgetTester tester) async {
466
    double? textScaleFactor;
467 468
    await tester.pumpWidget(MaterialApp(
      home: Builder(builder:(BuildContext context) {
469
        textScaleFactor = MediaQuery.of(context).textScaleFactor;
470
        return Container();
471 472 473 474 475
      }),
    ));
    expect(textScaleFactor, isNotNull);
    expect(textScaleFactor, equals(1.0));
  });
476 477

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

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

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

520 521 522 523
  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;

524
    late ThemeData appliedTheme;
525 526 527 528 529 530 531 532 533 534 535
    await tester.pumpWidget(
      MaterialApp(
        theme: ThemeData(
            brightness: Brightness.light
        ),
        darkTheme: ThemeData(
          brightness: Brightness.dark,
        ),
        themeMode: ThemeMode.light,
        home: Builder(
          builder: (BuildContext context) {
536
            appliedTheme = Theme.of(context);
537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556
            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(
            brightness: Brightness.light
        ),
        darkTheme: ThemeData(
          brightness: Brightness.dark,
        ),
        themeMode: ThemeMode.light,
        home: Builder(
          builder: (BuildContext context) {
557
            appliedTheme = Theme.of(context);
558 559 560 561 562 563 564 565 566 567 568 569
            return const SizedBox();
          },
        ),
      ),
    );
    expect(appliedTheme.brightness, Brightness.light);
  });

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

570
    late ThemeData appliedTheme;
571 572 573 574 575 576 577 578 579 580 581
    await tester.pumpWidget(
      MaterialApp(
        theme: ThemeData(
            brightness: Brightness.light
        ),
        darkTheme: ThemeData(
          brightness: Brightness.dark,
        ),
        themeMode: ThemeMode.dark,
        home: Builder(
          builder: (BuildContext context) {
582
            appliedTheme = Theme.of(context);
583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602
            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(
            brightness: Brightness.light
        ),
        darkTheme: ThemeData(
          brightness: Brightness.dark,
        ),
        themeMode: ThemeMode.dark,
        home: Builder(
          builder: (BuildContext context) {
603
            appliedTheme = Theme.of(context);
604 605 606 607 608 609 610 611 612
            return const SizedBox();
          },
        ),
      ),
    );
    expect(appliedTheme.brightness, Brightness.dark);
  });

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

617
    late ThemeData appliedTheme;
618 619 620 621 622 623 624 625 626

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

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

640 641 642 643
  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;

644
    late ThemeData appliedTheme;
645 646 647 648 649 650 651 652 653 654 655
    await tester.pumpWidget(
      MaterialApp(
        theme: ThemeData(
            brightness: Brightness.light
        ),
        darkTheme: ThemeData(
          brightness: Brightness.dark,
        ),
        themeMode: ThemeMode.system,
        home: Builder(
          builder: (BuildContext context) {
656
            appliedTheme = Theme.of(context);
657 658 659 660 661 662 663 664
            return const SizedBox();
          },
        ),
      ),
    );
    expect(appliedTheme.brightness, Brightness.dark);
  });

665 666 667 668 669
  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;

670
    late ThemeData appliedTheme;
671 672 673 674 675 676 677 678

    await tester.pumpWidget(
      MaterialApp(
        theme: ThemeData(
          brightness: Brightness.light
        ),
        home: Builder(
          builder: (BuildContext context) {
679
            appliedTheme = Theme.of(context);
680 681 682 683 684 685 686 687 688 689 690 691 692 693
            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;

694
    late ThemeData appliedTheme;
695 696 697 698 699

    await tester.pumpWidget(
      MaterialApp(
        home: Builder(
          builder: (BuildContext context) {
700
            appliedTheme = Theme.of(context);
701 702 703 704 705 706 707 708 709 710 711 712 713 714
            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;

715
    late ThemeData appliedTheme;
716 717 718 719 720 721 722 723

    await tester.pumpWidget(
      MaterialApp(
        darkTheme: ThemeData(
          brightness: Brightness.dark,
        ),
        home: Builder(
          builder: (BuildContext context) {
724
            appliedTheme = Theme.of(context);
725 726 727 728 729 730 731 732 733 734 735 736 737 738
            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;

739
    late ThemeData appliedTheme;
740 741 742 743 744 745 746 747 748 749 750

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

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

761 762 763 764
  testWidgets('MaterialApp uses high contrast theme when appropriate', (WidgetTester tester) async {
    tester.binding.window.platformBrightnessTestValue = Brightness.light;
    tester.binding.window.accessibilityFeaturesTestValue = MockAccessibilityFeature();

765
    late ThemeData appliedTheme;
766 767 768 769 770 771 772 773 774 775 776

    await tester.pumpWidget(
      MaterialApp(
        theme: ThemeData(
          primaryColor: Colors.lightBlue,
        ),
        highContrastTheme: ThemeData(
          primaryColor: Colors.blue,
        ),
        home: Builder(
          builder: (BuildContext context) {
777
            appliedTheme = Theme.of(context);
778 779 780 781 782 783 784
            return const SizedBox();
          },
        ),
      ),
    );

    expect(appliedTheme.primaryColor, Colors.blue);
785
    tester.binding.window.clearAccessibilityFeaturesTestValue();
786 787 788 789 790 791
  });

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

792
    late ThemeData appliedTheme;
793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809

    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) {
810
            appliedTheme = Theme.of(context);
811 812 813 814 815 816 817
            return const SizedBox();
          },
        ),
      ),
    );

    expect(appliedTheme.primaryColor, Colors.green);
818
    tester.binding.window.clearAccessibilityFeaturesTestValue();
819 820
  });

821 822 823 824
  testWidgets('MaterialApp uses dark theme when no high contrast dark theme is provided', (WidgetTester tester) async {
    tester.binding.window.platformBrightnessTestValue = Brightness.dark;
    tester.binding.window.accessibilityFeaturesTestValue = MockAccessibilityFeature();

825
    late ThemeData appliedTheme;
826 827 828 829 830 831 832 833 834 835 836

    await tester.pumpWidget(
      MaterialApp(
        theme: ThemeData(
          primaryColor: Colors.lightBlue,
        ),
        darkTheme: ThemeData(
          primaryColor: Colors.lightGreen,
        ),
        home: Builder(
          builder: (BuildContext context) {
837
            appliedTheme = Theme.of(context);
838 839 840 841 842 843 844
            return const SizedBox();
          },
        ),
      ),
    );

    expect(appliedTheme.primaryColor, Colors.lightGreen);
845 846
    tester.binding.window.clearAccessibilityFeaturesTestValue();
    tester.binding.window.clearPlatformBrightnessTestValue();
847 848
  });

849 850 851 852 853
  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;

854 855
    ThemeData? themeBeforeBrightnessChange;
    ThemeData? themeAfterBrightnessChange;
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

    await tester.pumpWidget(
      MaterialApp(
        theme: ThemeData(
          brightness: Brightness.light
        ),
        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();

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

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

  testWidgets('MaterialApp does create HeroController with the MaterialRectArcTween', (WidgetTester tester) async {
    final HeroController controller = MaterialApp.createMaterialHeroController();
965
    final Tween<Rect?> tween = controller.createRectTween!(
966 967 968 969 970
      const Rect.fromLTRB(0.0, 0.0, 10.0, 10.0),
      const Rect.fromLTRB(0.0, 0.0, 20.0, 20.0)
    );
    expect(tween, isA<MaterialRectArcTween>());
  });
971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986

  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);
  });
987 988 989 990 991 992 993 994 995

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

  testWidgets('MaterialApp.builder can build app without a Navigator', (WidgetTester tester) async {
1020
    Widget? builderChild;
1021
    await tester.pumpWidget(MaterialApp(
1022
      builder: (BuildContext context, Widget? child) {
1023 1024 1025 1026 1027 1028
        builderChild = child;
        return Container();
      },
    ));
    expect(builderChild, isNull);
  });
1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066

  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(
        scrollBehavior: MockScrollBehavior(),
        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);
  });
}

class MockScrollBehavior extends ScrollBehavior {
  @override
  ScrollPhysics getScrollPhysics(BuildContext context) => const NeverScrollableScrollPhysics();
1067
}
1068

1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087
class MockAccessibilityFeature implements AccessibilityFeatures {
  @override
  bool get accessibleNavigation => true;

  @override
  bool get boldText => true;

  @override
  bool get disableAnimations => true;

  @override
  bool get highContrast => true;

  @override
  bool get invertColors => true;

  @override
  bool get reduceMotion => true;
}
1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107

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({
1108 1109
    required this.builder,
    required this.onPopPage,
1110 1111 1112 1113 1114 1115
  });

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

  RouteInformation get routeInformation => _routeInformation;
1116
  late RouteInformation _routeInformation;
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
  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.
1143 1144
        const MaterialPage<void>(
          child: Text('base'),
1145 1146
        ),
        MaterialPage<void>(
1147
          key: ValueKey<String>(routeInformation.location!),
1148
          child: builder(context, routeInformation),
1149 1150 1151 1152 1153
        )
      ],
    );
  }
}