page_test.dart 48.2 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
@Tags(<String>['reduced-test-set'])
6
library;
7 8
import 'dart:ui' as ui;

9
import 'package:flutter/cupertino.dart' show CupertinoPageRoute;
10
import 'package:flutter/foundation.dart';
11
import 'package:flutter/material.dart';
12
import 'package:flutter/rendering.dart';
13
import 'package:flutter_test/flutter_test.dart';
14 15

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

void main() {
18
  testWidgets('test page transition (_FadeUpwardsPageTransition)', (WidgetTester tester) async {
19
    await tester.pumpWidget(
20
      MaterialApp(
21
        home: const Material(child: Text('Page 1')),
22 23 24 25 26 27 28
        theme: ThemeData(
          pageTransitionsTheme: const PageTransitionsTheme(
            builders: <TargetPlatform, PageTransitionsBuilder>{
              TargetPlatform.android: FadeUpwardsPageTransitionsBuilder(),
            },
          ),
        ),
29 30
        routes: <String, WidgetBuilder>{
          '/next': (BuildContext context) {
31
            return const Material(child: Text('Page 2'));
32
          },
33
        },
34
      ),
35 36
    );

37 38
    final Offset widget1TopLeft = tester.getTopLeft(find.text('Page 1'));

39 40
    tester.state<NavigatorState>(find.byType(Navigator)).pushNamed('/next');
    await tester.pump();
41
    await tester.pump(const Duration(milliseconds: 1));
42

43 44 45 46
    FadeTransition widget2Opacity =
        tester.element(find.text('Page 2')).findAncestorWidgetOfExactType<FadeTransition>()!;
    Offset widget2TopLeft = tester.getTopLeft(find.text('Page 2'));
    final Size widget2Size = tester.getSize(find.text('Page 2'));
47

48 49 50 51 52 53 54 55
    // Android transition is vertical only.
    expect(widget1TopLeft.dx == widget2TopLeft.dx, true);
    // Page 1 is above page 2 mid-transition.
    expect(widget1TopLeft.dy < widget2TopLeft.dy, true);
    // Animation begins 3/4 of the way up the page.
    expect(widget2TopLeft.dy < widget2Size.height / 4.0, true);
    // Animation starts with page 2 being near transparent.
    expect(widget2Opacity.opacity.value < 0.01, true);
56

57
    await tester.pump(const Duration(milliseconds: 300));
58 59 60 61 62 63 64

    // Page 2 covers page 1.
    expect(find.text('Page 1'), findsNothing);
    expect(find.text('Page 2'), isOnstage);

    tester.state<NavigatorState>(find.byType(Navigator)).pop();
    await tester.pump();
65
    await tester.pump(const Duration(milliseconds: 1));
66

67 68 69
    widget2Opacity =
        tester.element(find.text('Page 2')).findAncestorWidgetOfExactType<FadeTransition>()!;
    widget2TopLeft = tester.getTopLeft(find.text('Page 2'));
70

71 72 73 74
    // Page 2 starts to move down.
    expect(widget1TopLeft.dy < widget2TopLeft.dy, true);
    // Page 2 starts to lose opacity.
    expect(widget2Opacity.opacity.value < 1.0, true);
75

76
    await tester.pump(const Duration(milliseconds: 300));
77 78 79

    expect(find.text('Page 1'), isOnstage);
    expect(find.text('Page 2'), findsNothing);
80
  }, variant: TargetPlatformVariant.only(TargetPlatform.android));
81

82
  testWidgets('test page transition (CupertinoPageTransition)', (WidgetTester tester) async {
83
    final Key page2Key = UniqueKey();
84
    await tester.pumpWidget(
85
      MaterialApp(
86
        home: const Material(child: Text('Page 1')),
87 88
        routes: <String, WidgetBuilder>{
          '/next': (BuildContext context) {
89
            return Material(
90 91 92
              key: page2Key,
              child: const Text('Page 2'),
            );
93
          },
94
        },
95
      ),
96 97
    );

98
    final Offset widget1InitialTopLeft = tester.getTopLeft(find.text('Page 1'));
99 100

    tester.state<NavigatorState>(find.byType(Navigator)).pushNamed('/next');
101

102
    await tester.pump();
103
    await tester.pump(const Duration(milliseconds: 150));
104

105 106
    Offset widget1TransientTopLeft = tester.getTopLeft(find.text('Page 1'));
    Offset widget2TopLeft = tester.getTopLeft(find.text('Page 2'));
107
    final RenderDecoratedBox box = tester.element(find.byKey(page2Key))
108
        .findAncestorRenderObjectOfType<RenderDecoratedBox>()!;
109

110
    // Page 1 is moving to the left.
111
    expect(widget1TransientTopLeft.dx < widget1InitialTopLeft.dx, true);
112
    // Page 1 isn't moving vertically.
113
    expect(widget1TransientTopLeft.dy == widget1InitialTopLeft.dy, true);
114
    // iOS transition is horizontal only.
115
    expect(widget1InitialTopLeft.dy == widget2TopLeft.dy, true);
116
    // Page 2 is coming in from the right.
117
    expect(widget2TopLeft.dx > widget1InitialTopLeft.dx, true);
118 119 120 121 122 123 124 125 126 127 128
    // As explained in _CupertinoEdgeShadowPainter.paint the shadow is drawn
    // as a bunch of rects. The rects are covering an area to the left of
    // where the page 2 box is and a width of 5% of the page 2 box width.
    // `paints` tests relative to the painter's given canvas
    // rather than relative to the screen so assert that the shadow starts at
    // offset.dx = 0.
    final PaintPattern paintsShadow = paints;
    for (int i = 0; i < 0.05 * 800; i += 1) {
      paintsShadow.rect(rect: Rect.fromLTWH(-i.toDouble() - 1.0 , 0.0, 1.0, 600));
    }
    expect(box, paintsShadow);
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143

    await tester.pumpAndSettle();

    // Page 2 covers page 1.
    expect(find.text('Page 1'), findsNothing);
    expect(find.text('Page 2'), isOnstage);

    tester.state<NavigatorState>(find.byType(Navigator)).pop();
    await tester.pump();
    await tester.pump(const Duration(milliseconds: 100));

    widget1TransientTopLeft = tester.getTopLeft(find.text('Page 1'));
    widget2TopLeft = tester.getTopLeft(find.text('Page 2'));

    // Page 1 is coming back from the left.
144
    expect(widget1TransientTopLeft.dx < widget1InitialTopLeft.dx, true);
145
    // Page 1 isn't moving vertically.
146
    expect(widget1TransientTopLeft.dy == widget1InitialTopLeft.dy, true);
147
    // iOS transition is horizontal only.
148
    expect(widget1InitialTopLeft.dy == widget2TopLeft.dy, true);
149
    // Page 2 is leaving towards the right.
150
    expect(widget2TopLeft.dx > widget1InitialTopLeft.dx, true);
151 152 153 154 155 156 157 158 159 160

    await tester.pumpAndSettle();

    expect(find.text('Page 1'), isOnstage);
    expect(find.text('Page 2'), findsNothing);

    widget1TransientTopLeft = tester.getTopLeft(find.text('Page 1'));

    // Page 1 is back where it started.
    expect(widget1InitialTopLeft == widget1TransientTopLeft, true);
161
  }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }));
162

163 164 165
  testWidgets('test page transition (_ZoomPageTransition) without rasterization', (WidgetTester tester) async {
    Iterable<Layer> findLayers(Finder of) {
      return tester.layerListOf(
166
        find.ancestor(of: of, matching: find.byType(SnapshotWidget)).first,
167 168 169
      );
    }

170 171
    OpacityLayer findForwardFadeTransition(Finder of) {
      return findLayers(of).whereType<OpacityLayer>().first;
172 173
    }

174 175
    TransformLayer findForwardScaleTransition(Finder of) {
      return findLayers(of).whereType<TransformLayer>().first;
176 177 178 179
    }

    await tester.pumpWidget(
      MaterialApp(
180 181
        onGenerateRoute: (RouteSettings settings) {
          return MaterialPageRoute<void>(
182
            allowSnapshotting: false,
183 184 185 186 187 188 189
            builder: (BuildContext context) {
              if (settings.name == '/') {
                return const Material(child: Text('Page 1'));
              }
              return const Material(child: Text('Page 2'));
            },
          );
190 191 192 193 194 195 196 197
        },
      ),
    );

    tester.state<NavigatorState>(find.byType(Navigator)).pushNamed('/next');
    await tester.pump();
    await tester.pump(const Duration(milliseconds: 50));

198 199 200 201 202 203 204
    TransformLayer widget1Scale = findForwardScaleTransition(find.text('Page 1'));
    TransformLayer widget2Scale = findForwardScaleTransition(find.text('Page 2'));
    OpacityLayer widget2Opacity = findForwardFadeTransition(find.text('Page 2'));

    double getScale(TransformLayer layer) {
      return layer.transform!.storage[0];
    }
205 206

    // Page 1 is enlarging, starts from 1.0.
207
    expect(getScale(widget1Scale), greaterThan(1.0));
208
    // Page 2 is enlarging from the value less than 1.0.
209
    expect(getScale(widget2Scale), lessThan(1.0));
210
    // Page 2 is becoming none transparent.
211
    expect(widget2Opacity.alpha, lessThan(255));
212 213 214 215 216 217 218 219 220 221 222 223

    await tester.pump(const Duration(milliseconds: 250));
    await tester.pump(const Duration(milliseconds: 1));

    // Page 2 covers page 1.
    expect(find.text('Page 1'), findsNothing);
    expect(find.text('Page 2'), isOnstage);

    tester.state<NavigatorState>(find.byType(Navigator)).pop();
    await tester.pump();
    await tester.pump(const Duration(milliseconds: 100));

224 225 226
    widget1Scale = findForwardScaleTransition(find.text('Page 1'));
    widget2Scale = findForwardScaleTransition(find.text('Page 2'));
    widget2Opacity = findForwardFadeTransition(find.text('Page 2'));
227 228

    // Page 1 is narrowing down, but still larger than 1.0.
229
    expect(getScale(widget1Scale), greaterThan(1.0));
230
    // Page 2 is smaller than 1.0.
231
    expect(getScale(widget2Scale), lessThan(1.0));
232
    // Page 2 is becoming transparent.
233
    expect(widget2Opacity.alpha, lessThan(255));
234 235 236 237 238 239 240 241

    await tester.pump(const Duration(milliseconds: 200));
    await tester.pump(const Duration(milliseconds: 1));

    expect(find.text('Page 1'), isOnstage);
    expect(find.text('Page 2'), findsNothing);
  }, variant: TargetPlatformVariant.only(TargetPlatform.android));

242
  testWidgets('test page transition (_ZoomPageTransition) with rasterization re-rasterizes when window insets', (WidgetTester tester) async {
243
    late Size oldSize;
244
    late ui.WindowPadding oldInsets;
245 246
    try {
      oldSize = tester.binding.window.physicalSize;
247
      oldInsets = tester.binding.window.viewInsets;
248
      tester.binding.window.physicalSizeTestValue = const Size(1000, 1000);
249
      tester.binding.window.viewInsetsTestValue = ui.WindowPadding.zero;
250

251 252
      // Intentionally use nested scaffolds to simulate the view insets being
      // consumed.
253 254 255 256 257 258 259 260
      final Key key = GlobalKey();
      await tester.pumpWidget(
        RepaintBoundary(
          key: key,
          child: MaterialApp(
            onGenerateRoute: (RouteSettings settings) {
              return MaterialPageRoute<void>(
                builder: (BuildContext context) {
261 262 263
                  return const Scaffold(body: Scaffold(
                    body: Material(child: SizedBox.shrink())
                  ));
264 265 266 267 268 269 270 271 272 273 274 275 276
                },
              );
            },
          ),
        ),
      );

      tester.state<NavigatorState>(find.byType(Navigator)).pushNamed('/next');
      await tester.pump();
      await tester.pump(const Duration(milliseconds: 50));

      await expectLater(find.byKey(key), matchesGoldenFile('zoom_page_transition.small.png'));

277 278
       // Change the view insets
      tester.binding.window.viewInsetsTestValue = const TestWindowPadding(left: 0, top: 0, right: 0, bottom: 500);
279 280 281 282 283 284 285

      await tester.pump();
      await tester.pump(const Duration(milliseconds: 50));

      await expectLater(find.byKey(key), matchesGoldenFile('zoom_page_transition.big.png'));
    } finally {
      tester.binding.window.physicalSizeTestValue = oldSize;
286
      tester.binding.window.viewInsetsTestValue = oldInsets;
287 288 289
    }
  }, variant: TargetPlatformVariant.only(TargetPlatform.android), skip: kIsWeb); // [intended] rasterization is not used on the web.

290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372

  testWidgets(
      'test page transition (_ZoomPageTransition) with rasterization disables snapshotting for enter route',
      (WidgetTester tester) async {
    Iterable<Layer> findLayers(Finder of) {
      return tester.layerListOf(
        find.ancestor(of: of, matching: find.byType(SnapshotWidget)).first,
      );
    }

    bool isTransitioningWithoutSnapshotting(Finder of) {
      // When snapshotting is off, the OpacityLayer and TransformLayer will be
      // applied directly.
      final Iterable<Layer> layers = findLayers(of);
      return layers.whereType<OpacityLayer>().length == 1 &&
          layers.whereType<TransformLayer>().length == 1;
    }

    bool isSnapshotted(Finder of) {
      final Iterable<Layer> layers = findLayers(of);
      // The scrim and the snapshot image are the only two layers.
      return layers.length == 2 &&
          layers.whereType<OffsetLayer>().length == 1 &&
          layers.whereType<PictureLayer>().length == 1;
    }

    await tester.pumpWidget(
      MaterialApp(
        routes: <String, WidgetBuilder>{
          '/1': (_) => const Material(child: Text('Page 1')),
          '/2': (_) => const Material(child: Text('Page 2')),
        },
        initialRoute: '/1',
        builder: (BuildContext context, Widget? child) {
          final ThemeData themeData = Theme.of(context);
          return Theme(
            data: themeData.copyWith(
              pageTransitionsTheme: PageTransitionsTheme(
                builders: <TargetPlatform, PageTransitionsBuilder>{
                  ...themeData.pageTransitionsTheme.builders,
                  TargetPlatform.android: const ZoomPageTransitionsBuilder(
                    allowEnterRouteSnapshotting: false,
                  ),
                },
              ),
            ),
            child: Builder(builder: (_) => child!),
          );
        },
      ),
    );

    final Finder page1Finder = find.text('Page 1');
    final Finder page2Finder = find.text('Page 2');

    // Page 1 on top.
    expect(isSnapshotted(page1Finder), isFalse);

    // Transitioning from page 1 to page 2.
    tester.state<NavigatorState>(find.byType(Navigator)).pushNamed('/2');
    await tester.pump();
    await tester.pump(const Duration(milliseconds: 50));

    expect(isSnapshotted(page1Finder), isTrue);
    expect(isTransitioningWithoutSnapshotting(page2Finder), isTrue);

    // Page 2 on top.
    await tester.pumpAndSettle();
    expect(isSnapshotted(page2Finder), isFalse);

    // Transitioning back from page 2 to page 1.
    tester.state<NavigatorState>(find.byType(Navigator)).pop();
    await tester.pump();
    await tester.pump(const Duration(milliseconds: 50));

    expect(isTransitioningWithoutSnapshotting(page1Finder), isTrue);
    expect(isSnapshotted(page2Finder), isTrue);

    // Page 1 on top.
    await tester.pumpAndSettle();
    expect(isSnapshotted(page1Finder), isFalse);
  }, variant: TargetPlatformVariant.only(TargetPlatform.android), skip: kIsWeb); // [intended] rasterization is not used on the web.

Dan Field's avatar
Dan Field committed
373
  testWidgets('test fullscreen dialog transition', (WidgetTester tester) async {
374
    await tester.pumpWidget(
Dan Field's avatar
Dan Field committed
375 376
      const MaterialApp(
        home: Material(child: Text('Page 1')),
377
      ),
378 379
    );

380
    final Offset widget1InitialTopLeft = tester.getTopLeft(find.text('Page 1'));
381

382
    tester.state<NavigatorState>(find.byType(Navigator)).push(MaterialPageRoute<void>(
383
      builder: (BuildContext context) {
384
        return const Material(child: Text('Page 2'));
385 386 387 388 389 390 391
      },
      fullscreenDialog: true,
    ));

    await tester.pump();
    await tester.pump(const Duration(milliseconds: 100));

392 393
    Offset widget1TransientTopLeft = tester.getTopLeft(find.text('Page 1'));
    Offset widget2TopLeft = tester.getTopLeft(find.text('Page 2'));
394 395 396 397

    // Page 1 doesn't move.
    expect(widget1TransientTopLeft == widget1InitialTopLeft, true);
    // Fullscreen dialogs transitions vertically only.
398
    expect(widget1InitialTopLeft.dx == widget2TopLeft.dx, true);
399
    // Page 2 is coming in from the bottom.
400
    expect(widget2TopLeft.dy > widget1InitialTopLeft.dy, true);
401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417

    await tester.pumpAndSettle();

    // Page 2 covers page 1.
    expect(find.text('Page 1'), findsNothing);
    expect(find.text('Page 2'), isOnstage);

    tester.state<NavigatorState>(find.byType(Navigator)).pop();
    await tester.pump();
    await tester.pump(const Duration(milliseconds: 100));

    widget1TransientTopLeft = tester.getTopLeft(find.text('Page 1'));
    widget2TopLeft = tester.getTopLeft(find.text('Page 2'));

    // Page 1 doesn't move.
    expect(widget1TransientTopLeft == widget1InitialTopLeft, true);
    // Fullscreen dialogs transitions vertically only.
418
    expect(widget1InitialTopLeft.dx == widget2TopLeft.dx, true);
419
    // Page 2 is leaving towards the bottom.
420
    expect(widget2TopLeft.dy > widget1InitialTopLeft.dy, true);
421 422 423 424 425 426 427 428 429 430

    await tester.pumpAndSettle();

    expect(find.text('Page 1'), isOnstage);
    expect(find.text('Page 2'), findsNothing);

    widget1TransientTopLeft = tester.getTopLeft(find.text('Page 1'));

    // Page 1 is back where it started.
    expect(widget1InitialTopLeft == widget1TransientTopLeft, true);
431
  }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }));
432 433 434

  testWidgets('test no back gesture on Android', (WidgetTester tester) async {
    await tester.pumpWidget(
435
      MaterialApp(
436
        home: const Scaffold(body: Text('Page 1')),
437 438
        routes: <String, WidgetBuilder>{
          '/next': (BuildContext context) {
439
            return const Scaffold(body: Text('Page 2'));
440 441
          },
        },
442
      ),
443 444 445 446 447 448 449 450 451
    );

    tester.state<NavigatorState>(find.byType(Navigator)).pushNamed('/next');
    await tester.pumpAndSettle();

    expect(find.text('Page 1'), findsNothing);
    expect(find.text('Page 2'), isOnstage);

    // Drag from left edge to invoke the gesture.
452
    final TestGesture gesture = await tester.startGesture(const Offset(5.0, 100.0));
453
    await gesture.moveBy(const Offset(400.0, 0.0));
454
    await tester.pump();
455 456 457 458 459

    expect(find.text('Page 1'), findsNothing);
    expect(find.text('Page 2'), isOnstage);

    // Page 2 didn't move
460
    expect(tester.getTopLeft(find.text('Page 2')), Offset.zero);
461
  }, variant: TargetPlatformVariant.only(TargetPlatform.android));
462

Dan Field's avatar
Dan Field committed
463
  testWidgets('test back gesture', (WidgetTester tester) async {
464
    await tester.pumpWidget(
465
      MaterialApp(
466
        home: const Scaffold(body: Text('Page 1')),
467 468
        routes: <String, WidgetBuilder>{
          '/next': (BuildContext context) {
469
            return const Scaffold(body: Text('Page 2'));
470 471
          },
        },
472
      ),
473 474 475 476 477 478 479 480 481
    );

    tester.state<NavigatorState>(find.byType(Navigator)).pushNamed('/next');
    await tester.pumpAndSettle();

    expect(find.text('Page 1'), findsNothing);
    expect(find.text('Page 2'), isOnstage);

    // Drag from left edge to invoke the gesture.
482
    final TestGesture gesture = await tester.startGesture(const Offset(5.0, 100.0));
483
    await gesture.moveBy(const Offset(400.0, 0.0));
484
    await tester.pump();
485 486 487 488

    // Page 1 is now visible.
    expect(find.text('Page 1'), isOnstage);
    expect(find.text('Page 2'), isOnstage);
489 490

    // The route widget position needs to track the finger position very exactly.
491
    expect(tester.getTopLeft(find.text('Page 2')), const Offset(400.0, 0.0));
492 493 494 495

    await gesture.moveBy(const Offset(-200.0, 0.0));
    await tester.pump();

496
    expect(tester.getTopLeft(find.text('Page 2')), const Offset(200.0, 0.0));
497 498 499 500

    await gesture.moveBy(const Offset(-100.0, 200.0));
    await tester.pump();

501
    expect(tester.getTopLeft(find.text('Page 2')), const Offset(100.0, 0.0));
502
  }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }));
503

504 505
  testWidgets('back gesture while OS changes', (WidgetTester tester) async {
    final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{
506
      '/': (BuildContext context) => Material(
507
        child: TextButton(
508
          child: const Text('PUSH'),
509
          onPressed: () { Navigator.of(context).pushNamed('/b'); },
510 511
        ),
      ),
512
      '/b': (BuildContext context) => const Text('HELLO'),
513 514
    };
    await tester.pumpWidget(
515 516
      MaterialApp(
        theme: ThemeData(platform: TargetPlatform.iOS),
517 518 519 520
        routes: routes,
      ),
    );
    await tester.tap(find.text('PUSH'));
521
    expect(await tester.pumpAndSettle(const Duration(minutes: 1)), 2);
522 523 524 525 526 527 528 529 530 531 532 533 534 535
    expect(find.text('PUSH'), findsNothing);
    expect(find.text('HELLO'), findsOneWidget);
    final Offset helloPosition1 = tester.getCenter(find.text('HELLO'));
    final TestGesture gesture = await tester.startGesture(const Offset(2.5, 300.0));
    await tester.pump(const Duration(milliseconds: 20));
    await gesture.moveBy(const Offset(100.0, 0.0));
    expect(find.text('PUSH'), findsNothing);
    expect(find.text('HELLO'), findsOneWidget);
    await tester.pump(const Duration(milliseconds: 20));
    expect(find.text('PUSH'), findsOneWidget);
    expect(find.text('HELLO'), findsOneWidget);
    final Offset helloPosition2 = tester.getCenter(find.text('HELLO'));
    expect(helloPosition1.dx, lessThan(helloPosition2.dx));
    expect(helloPosition1.dy, helloPosition2.dy);
536
    expect(Theme.of(tester.element(find.text('HELLO'))).platform, TargetPlatform.iOS);
537
    await tester.pumpWidget(
538 539
      MaterialApp(
        theme: ThemeData(platform: TargetPlatform.android),
540 541 542 543 544 545 546 547 548 549 550 551
        routes: routes,
      ),
    );
    // Now we have to let the theme animation run through.
    // This takes three frames (including the first one above):
    //  1. Start the Theme animation. It's at t=0 so everything else is identical.
    //  2. Start any animations that are informed by the Theme, for example, the
    //     DefaultTextStyle, on the first frame that the theme is not at t=0. In
    //     this case, it's at t=1.0 of the theme animation, so this is also the
    //     frame in which the theme animation ends.
    //  3. End all the other animations.
    expect(await tester.pumpAndSettle(const Duration(minutes: 1)), 2);
552
    expect(Theme.of(tester.element(find.text('HELLO'))).platform, TargetPlatform.android);
553 554 555 556 557 558 559 560 561 562 563 564 565
    final Offset helloPosition3 = tester.getCenter(find.text('HELLO'));
    expect(helloPosition3, helloPosition2);
    expect(find.text('PUSH'), findsOneWidget);
    expect(find.text('HELLO'), findsOneWidget);
    await gesture.moveBy(const Offset(100.0, 0.0));
    await tester.pump(const Duration(milliseconds: 20));
    expect(find.text('PUSH'), findsOneWidget);
    expect(find.text('HELLO'), findsOneWidget);
    final Offset helloPosition4 = tester.getCenter(find.text('HELLO'));
    expect(helloPosition3.dx, lessThan(helloPosition4.dx));
    expect(helloPosition3.dy, helloPosition4.dy);
    await gesture.moveBy(const Offset(500.0, 0.0));
    await gesture.up();
566
    expect(await tester.pumpAndSettle(const Duration(minutes: 1)), 3);
567 568
    expect(find.text('PUSH'), findsOneWidget);
    expect(find.text('HELLO'), findsNothing);
569 570

    await tester.pumpWidget(
571
      MaterialApp(
Dan Field's avatar
Dan Field committed
572 573 574 575 576 577 578 579 580 581 582 583 584 585 586
        theme: ThemeData(platform: TargetPlatform.macOS),
        routes: routes,
      ),
    );
    await tester.tap(find.text('PUSH'));
    expect(await tester.pumpAndSettle(const Duration(minutes: 1)), 2);
    expect(find.text('PUSH'), findsNothing);
    expect(find.text('HELLO'), findsOneWidget);
    final Offset helloPosition5 = tester.getCenter(find.text('HELLO'));
    await gesture.down(const Offset(2.5, 300.0));
    await tester.pump(const Duration(milliseconds: 20));
    await gesture.moveBy(const Offset(100.0, 0.0));
    expect(find.text('PUSH'), findsNothing);
    expect(find.text('HELLO'), findsOneWidget);
    await tester.pump(const Duration(milliseconds: 20));
587
    expect(find.text('PUSH'), findsOneWidget);
Dan Field's avatar
Dan Field committed
588 589
    expect(find.text('HELLO'), findsOneWidget);
    final Offset helloPosition6 = tester.getCenter(find.text('HELLO'));
590 591
    expect(helloPosition5.dx, lessThan(helloPosition6.dx));
    expect(helloPosition5.dy, helloPosition6.dy);
592
    expect(Theme.of(tester.element(find.text('HELLO'))).platform, TargetPlatform.macOS);
593
  });
Dan Field's avatar
Dan Field committed
594 595 596 597 598

  testWidgets('test no back gesture on fullscreen dialogs', (WidgetTester tester) async {
    await tester.pumpWidget(
      const MaterialApp(
        home: Scaffold(body: Text('Page 1')),
599
      ),
600 601
    );

602
    tester.state<NavigatorState>(find.byType(Navigator)).push(MaterialPageRoute<void>(
603
      builder: (BuildContext context) {
604
        return const Scaffold(body: Text('Page 2'));
605 606 607 608 609 610 611 612 613
      },
      fullscreenDialog: true,
    ));
    await tester.pumpAndSettle();

    expect(find.text('Page 1'), findsNothing);
    expect(find.text('Page 2'), isOnstage);

    // Drag from left edge to invoke the gesture.
614
    final TestGesture gesture = await tester.startGesture(const Offset(5.0, 100.0));
615
    await gesture.moveBy(const Offset(400.0, 0.0));
616
    await tester.pump();
617 618 619 620 621

    expect(find.text('Page 1'), findsNothing);
    expect(find.text('Page 2'), isOnstage);

    // Page 2 didn't move
622
    expect(tester.getTopLeft(find.text('Page 2')), Offset.zero);
Dan Field's avatar
Dan Field committed
623
  }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS,  TargetPlatform.macOS }));
624 625 626

  testWidgets('test adaptable transitions switch during execution', (WidgetTester tester) async {
    await tester.pumpWidget(
627
      MaterialApp(
628 629 630 631 632 633 634 635
        theme: ThemeData(
          platform: TargetPlatform.android,
          pageTransitionsTheme: const PageTransitionsTheme(
            builders: <TargetPlatform, PageTransitionsBuilder>{
              TargetPlatform.android: FadeUpwardsPageTransitionsBuilder(),
            },
          ),
        ),
636
        home: const Material(child: Text('Page 1')),
637 638
        routes: <String, WidgetBuilder>{
          '/next': (BuildContext context) {
639
            return const Material(child: Text('Page 2'));
640 641
          },
        },
642
      ),
643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668
    );

    final Offset widget1InitialTopLeft = tester.getTopLeft(find.text('Page 1'));

    tester.state<NavigatorState>(find.byType(Navigator)).pushNamed('/next');
    await tester.pump();
    await tester.pump(const Duration(milliseconds: 100));

    Offset widget2TopLeft = tester.getTopLeft(find.text('Page 2'));
    final Size widget2Size = tester.getSize(find.text('Page 2'));

    // Android transition is vertical only.
    expect(widget1InitialTopLeft.dx == widget2TopLeft.dx, true);
    // Page 1 is above page 2 mid-transition.
    expect(widget1InitialTopLeft.dy < widget2TopLeft.dy, true);
    // Animation begins from the top of the page.
    expect(widget2TopLeft.dy < widget2Size.height, true);

    await tester.pump(const Duration(milliseconds: 300));

    // Page 2 covers page 1.
    expect(find.text('Page 1'), findsNothing);
    expect(find.text('Page 2'), isOnstage);

    // Re-pump the same app but with iOS instead of Android.
    await tester.pumpWidget(
669
      MaterialApp(
670
        home: const Material(child: Text('Page 1')),
671 672
        routes: <String, WidgetBuilder>{
          '/next': (BuildContext context) {
673
            return const Material(child: Text('Page 2'));
674 675
          },
        },
676
      ),
677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703
    );

    tester.state<NavigatorState>(find.byType(Navigator)).pop();
    await tester.pump();
    await tester.pump(const Duration(milliseconds: 100));

    Offset widget1TransientTopLeft = tester.getTopLeft(find.text('Page 1'));
    widget2TopLeft = tester.getTopLeft(find.text('Page 2'));

    // Page 1 is coming back from the left.
    expect(widget1TransientTopLeft.dx < widget1InitialTopLeft.dx, true);
    // Page 1 isn't moving vertically.
    expect(widget1TransientTopLeft.dy == widget1InitialTopLeft.dy, true);
    // iOS transition is horizontal only.
    expect(widget1InitialTopLeft.dy == widget2TopLeft.dy, true);
    // Page 2 is leaving towards the right.
    expect(widget2TopLeft.dx > widget1InitialTopLeft.dx, true);

    await tester.pump(const Duration(milliseconds: 300));

    expect(find.text('Page 1'), isOnstage);
    expect(find.text('Page 2'), findsNothing);

    widget1TransientTopLeft = tester.getTopLeft(find.text('Page 1'));

    // Page 1 is back where it started.
    expect(widget1InitialTopLeft == widget1TransientTopLeft, true);
704
  }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS,  TargetPlatform.macOS }));
705

Dan Field's avatar
Dan Field committed
706
  testWidgets('test edge swipe then drop back at starting point works', (WidgetTester tester) async {
707 708 709 710 711 712 713 714
    await tester.pumpWidget(
      MaterialApp(
        onGenerateRoute: (RouteSettings settings) {
          return MaterialPageRoute<void>(
            settings: settings,
            builder: (BuildContext context) {
              final String pageNumber = settings.name == '/' ? '1' : '2';
              return Center(child: Text('Page $pageNumber'));
715
            },
716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738
          );
        },
      ),
    );

    tester.state<NavigatorState>(find.byType(Navigator)).pushNamed('/next');

    await tester.pump();
    await tester.pump(const Duration(seconds: 1));

    expect(find.text('Page 1'), findsNothing);
    expect(find.text('Page 2'), isOnstage);

    final TestGesture gesture = await tester.startGesture(const Offset(5, 200));
    await gesture.moveBy(const Offset(300, 0));
    await tester.pump();
    // Bring it exactly back such that there's nothing to animate when releasing.
    await gesture.moveBy(const Offset(-300, 0));
    await gesture.up();
    await tester.pump();

    expect(find.text('Page 1'), findsNothing);
    expect(find.text('Page 2'), isOnstage);
Dan Field's avatar
Dan Field committed
739
  }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS,  TargetPlatform.macOS }));
740

Dan Field's avatar
Dan Field committed
741
  testWidgets('test edge swipe then drop back at ending point works', (WidgetTester tester) async {
742 743 744 745 746 747 748 749
    await tester.pumpWidget(
      MaterialApp(
        onGenerateRoute: (RouteSettings settings) {
          return MaterialPageRoute<void>(
            settings: settings,
            builder: (BuildContext context) {
              final String pageNumber = settings.name == '/' ? '1' : '2';
              return Center(child: Text('Page $pageNumber'));
750
            },
751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771
          );
        },
      ),
    );

    tester.state<NavigatorState>(find.byType(Navigator)).pushNamed('/next');

    await tester.pump();
    await tester.pump(const Duration(seconds: 1));

    expect(find.text('Page 1'), findsNothing);
    expect(find.text('Page 2'), isOnstage);

    final TestGesture gesture = await tester.startGesture(const Offset(5, 200));
    // The width of the page.
    await gesture.moveBy(const Offset(800, 0));
    await gesture.up();
    await tester.pump();

    expect(find.text('Page 1'), isOnstage);
    expect(find.text('Page 2'), findsNothing);
772
  }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS,  TargetPlatform.macOS }));
773 774 775 776 777 778 779 780 781 782

  testWidgets('Back swipe dismiss interrupted by route push', (WidgetTester tester) async {
    // Regression test for https://github.com/flutter/flutter/issues/28728
    final GlobalKey scaffoldKey = GlobalKey();

    await tester.pumpWidget(
      MaterialApp(
        home: Scaffold(
          key: scaffoldKey,
          body: Center(
783
            child: ElevatedButton(
784
              onPressed: () {
785
                Navigator.push<void>(scaffoldKey.currentContext!, MaterialPageRoute<void>(
786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828
                  builder: (BuildContext context) {
                    return const Scaffold(
                      body: Center(child: Text('route')),
                    );
                  },
                ));
              },
              child: const Text('push'),
            ),
          ),
        ),
      ),
    );

    // Check the basic iOS back-swipe dismiss transition. Dragging the pushed
    // route halfway across the screen will trigger the iOS dismiss animation

    await tester.tap(find.text('push'));
    await tester.pumpAndSettle();
    expect(find.text('route'), findsOneWidget);
    expect(find.text('push'), findsNothing);

    TestGesture gesture = await tester.startGesture(const Offset(5, 300));
    await gesture.moveBy(const Offset(400, 0));
    await gesture.up();
    await tester.pump();
    expect( // The 'route' route has been dragged to the right, halfway across the screen
      tester.getTopLeft(find.ancestor(of: find.text('route'), matching: find.byType(Scaffold))),
      const Offset(400, 0),
    );
    expect( // The 'push' route is sliding in from the left.
      tester.getTopLeft(find.ancestor(of: find.text('push'), matching: find.byType(Scaffold))).dx,
      lessThan(0),
    );
    await tester.pumpAndSettle();
    expect(find.text('push'), findsOneWidget);
    expect(
      tester.getTopLeft(find.ancestor(of: find.text('push'), matching: find.byType(Scaffold))),
      Offset.zero,
    );
    expect(find.text('route'), findsNothing);


829 830 831
    // Run the dismiss animation 60%, which exposes the route "push" button,
    // and then press the button. A drag dropped animation is 400ms when dropped
    // exactly halfway. It follows a curve that is very steep initially.
832 833 834 835 836 837 838

    await tester.tap(find.text('push'));
    await tester.pumpAndSettle();
    expect(find.text('route'), findsOneWidget);
    expect(find.text('push'), findsNothing);

    gesture = await tester.startGesture(const Offset(5, 300));
839
    await gesture.moveBy(const Offset(400, 0)); // Drag halfway.
840
    await gesture.up();
841 842 843 844 845 846 847 848 849 850 851
    await tester.pump(); // Trigger the dropped snapping animation.
    expect(
      tester.getTopLeft(find.ancestor(of: find.text('route'), matching: find.byType(Scaffold))),
      const Offset(400, 0),
    );
    // Let the dismissing snapping animation go 60%.
    await tester.pump(const Duration(milliseconds: 240));
    expect(
      tester.getTopLeft(find.ancestor(of: find.text('route'), matching: find.byType(Scaffold))).dx,
      moreOrLessEquals(798, epsilon: 1),
    );
852 853 854 855

    // Use the navigator to push a route instead of tapping the 'push' button.
    // The topmost route (the one that's animating away), ignores input while
    // the pop is underway because route.navigator.userGestureInProgress.
856
    Navigator.push<void>(scaffoldKey.currentContext!, MaterialPageRoute<void>(
857 858 859 860 861 862 863
      builder: (BuildContext context) {
        return const Scaffold(
          body: Center(child: Text('route')),
        );
      },
    ));

864 865 866
    await tester.pumpAndSettle();
    expect(find.text('route'), findsOneWidget);
    expect(find.text('push'), findsNothing);
867
  }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS,  TargetPlatform.macOS }));
868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883

  testWidgets('During back swipe the route ignores input', (WidgetTester tester) async {
    // Regression test for https://github.com/flutter/flutter/issues/39989

    final GlobalKey homeScaffoldKey = GlobalKey();
    final GlobalKey pageScaffoldKey = GlobalKey();
    int homeTapCount = 0;
    int pageTapCount = 0;

    await tester.pumpWidget(
      MaterialApp(
        home: Scaffold(
          key: homeScaffoldKey,
          body: GestureDetector(
            onTap: () {
              homeTapCount += 1;
884
            },
885 886 887 888 889 890 891 892 893
          ),
        ),
      ),
    );

    await tester.tap(find.byKey(homeScaffoldKey));
    expect(homeTapCount, 1);
    expect(pageTapCount, 0);

894
    Navigator.push<void>(homeScaffoldKey.currentContext!, MaterialPageRoute<void>(
895 896 897 898 899 900 901 902 903
      builder: (BuildContext context) {
        return Scaffold(
          key: pageScaffoldKey,
          appBar: AppBar(title: const Text('Page')),
          body: Padding(
            padding: const EdgeInsets.all(16),
            child: GestureDetector(
              onTap: () {
                pageTapCount += 1;
904
              },
905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927
            ),
          ),
        );
      },
    ));

    await tester.pumpAndSettle();
    await tester.tap(find.byKey(pageScaffoldKey));
    expect(homeTapCount, 1);
    expect(pageTapCount, 1);

    // Start the basic iOS back-swipe dismiss transition. Drag the pushed
    // "page" route halfway across the screen. The underlying "home" will
    // start sliding in from the left.

    final TestGesture gesture = await tester.startGesture(const Offset(5, 300));
    await gesture.moveBy(const Offset(400, 0));
    await tester.pump();
    expect(tester.getTopLeft(find.byKey(pageScaffoldKey)), const Offset(400, 0));
    expect(tester.getTopLeft(find.byKey(homeScaffoldKey)).dx, lessThan(0));

    // Tapping on the "page" route doesn't trigger the GestureDetector because
    // it's being dragged.
928
    await tester.tap(find.byKey(pageScaffoldKey), warnIfMissed: false);
929 930 931 932
    expect(homeTapCount, 1);
    expect(pageTapCount, 1);

    // Tapping the "page" route's back button doesn't do anything either.
933
    await tester.tap(find.byTooltip('Back'), warnIfMissed: false);
934 935
    await tester.pumpAndSettle();
    expect(tester.getTopLeft(find.byKey(pageScaffoldKey)), const Offset(400, 0));
936
    expect(tester.getTopLeft(find.byKey(homeScaffoldKey)).dx, lessThan(0));
937
  }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS,  TargetPlatform.macOS }));
938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953

  testWidgets('After a pop caused by a back-swipe, input reaches the exposed route', (WidgetTester tester) async {
    // Regression test for https://github.com/flutter/flutter/issues/41024

    final GlobalKey homeScaffoldKey = GlobalKey();
    final GlobalKey pageScaffoldKey = GlobalKey();
    int homeTapCount = 0;
    int pageTapCount = 0;

    await tester.pumpWidget(
      MaterialApp(
        home: Scaffold(
          key: homeScaffoldKey,
          body: GestureDetector(
            onTap: () {
              homeTapCount += 1;
954
            },
955 956 957 958 959 960 961 962 963
          ),
        ),
      ),
    );

    await tester.tap(find.byKey(homeScaffoldKey));
    expect(homeTapCount, 1);
    expect(pageTapCount, 0);

964
    final ValueNotifier<bool> notifier = Navigator.of(homeScaffoldKey.currentContext!).userGestureInProgressNotifier;
965 966
    expect(notifier.value, false);

967
    Navigator.push<void>(homeScaffoldKey.currentContext!, MaterialPageRoute<void>(
968 969 970 971 972 973 974 975 976
      builder: (BuildContext context) {
        return Scaffold(
          key: pageScaffoldKey,
          appBar: AppBar(title: const Text('Page')),
          body: Padding(
            padding: const EdgeInsets.all(16),
            child: GestureDetector(
              onTap: () {
                pageTapCount += 1;
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
            ),
          ),
        );
      },
    ));

    await tester.pumpAndSettle();
    await tester.tap(find.byKey(pageScaffoldKey));
    expect(homeTapCount, 1);
    expect(pageTapCount, 1);

    // Trigger the basic iOS back-swipe dismiss transition. Drag the pushed
    // "page" route more than halfway across the screen and then release it.

    final TestGesture gesture = await tester.startGesture(const Offset(5, 300));
    await gesture.moveBy(const Offset(500, 0));
    await tester.pump();
    expect(tester.getTopLeft(find.byKey(pageScaffoldKey)), const Offset(500, 0));
    expect(tester.getTopLeft(find.byKey(homeScaffoldKey)).dx, lessThan(0));
    expect(notifier.value, true);
    await gesture.up();
    await tester.pumpAndSettle();
    expect(notifier.value, false);
    expect(find.byKey(pageScaffoldKey), findsNothing);

    // The back-swipe dismiss pop transition has finished and input on the
    // home page still works.
    await tester.tap(find.byKey(homeScaffoldKey));
    expect(homeTapCount, 2);
    expect(pageTapCount, 1);
1008
  }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS,  TargetPlatform.macOS }));
1009

Dan Field's avatar
Dan Field committed
1010
  testWidgets('A MaterialPageRoute should slide out with CupertinoPageTransition when a compatible PageRoute is pushed on top of it', (WidgetTester tester) async {
1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035
    // Regression test for https://github.com/flutter/flutter/issues/44864.

    await tester.pumpWidget(
      MaterialApp(
        theme: ThemeData(platform: TargetPlatform.iOS),
        home: Scaffold(
          appBar: AppBar(title: const Text('Title')),
        ),
      ),
    );

    final Offset titleInitialTopLeft = tester.getTopLeft(find.text('Title'));

    tester.state<NavigatorState>(find.byType(Navigator)).push<void>(
      CupertinoPageRoute<void>(builder: (BuildContext context) => const Placeholder()),
    );

    await tester.pump();
    await tester.pump(const Duration(milliseconds: 150));

    final Offset titleTransientTopLeft = tester.getTopLeft(find.text('Title'));

    // Title of the first route slides to the left.
    expect(titleInitialTopLeft.dy, equals(titleTransientTopLeft.dy));
    expect(titleInitialTopLeft.dx, greaterThan(titleTransientTopLeft.dx));
1036
  }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS,  TargetPlatform.macOS }));
1037 1038 1039 1040 1041

  testWidgets('MaterialPage works', (WidgetTester tester) async {
    final LocalKey pageKey = UniqueKey();
    final TransitionDetector detector = TransitionDetector();
    List<Page<void>> myPages = <Page<void>>[
1042
      MaterialPage<void>(key: pageKey, child: const Text('first')),
1043 1044 1045 1046
    ];
    await tester.pumpWidget(
      buildNavigator(
        pages: myPages,
1047 1048 1049 1050
        onPopPage: (Route<dynamic> route, dynamic result) {
          assert(false); // The test should never execute this.
          return true;
        },
1051
        transitionDelegate: detector,
1052
      ),
1053 1054 1055 1056 1057 1058
    );

    expect(detector.hasTransition, isFalse);
    expect(find.text('first'), findsOneWidget);

    myPages = <Page<void>>[
1059
      MaterialPage<void>(key: pageKey, child: const Text('second')),
1060 1061 1062 1063 1064
    ];

    await tester.pumpWidget(
      buildNavigator(
        pages: myPages,
1065 1066 1067 1068
        onPopPage: (Route<dynamic> route, dynamic result) {
          assert(false); // The test should never execute this.
          return true;
        },
1069
        transitionDelegate: detector,
1070
      ),
1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083
    );
    // There should be no transition because the page has the same key.
    expect(detector.hasTransition, isFalse);
    // The content does update.
    expect(find.text('first'), findsNothing);
    expect(find.text('second'), findsOneWidget);
  });

  testWidgets('MaterialPage can toggle MaintainState', (WidgetTester tester) async {
    final LocalKey pageKeyOne = UniqueKey();
    final LocalKey pageKeyTwo = UniqueKey();
    final TransitionDetector detector = TransitionDetector();
    List<Page<void>> myPages = <Page<void>>[
1084 1085
      MaterialPage<void>(key: pageKeyOne, maintainState: false, child: const Text('first')),
      MaterialPage<void>(key: pageKeyTwo, child: const Text('second')),
1086 1087 1088 1089
    ];
    await tester.pumpWidget(
      buildNavigator(
        pages: myPages,
1090 1091 1092 1093
        onPopPage: (Route<dynamic> route, dynamic result) {
          assert(false); // The test should never execute this.
          return true;
        },
1094
        transitionDelegate: detector,
1095
      ),
1096 1097 1098 1099 1100 1101 1102 1103
    );

    expect(detector.hasTransition, isFalse);
    // Page one does not maintain state.
    expect(find.text('first', skipOffstage: false), findsNothing);
    expect(find.text('second'), findsOneWidget);

    myPages = <Page<void>>[
1104
      MaterialPage<void>(key: pageKeyOne, child: const Text('first')),
1105
      MaterialPage<void>(key: pageKeyTwo, child: const Text('second')),
1106 1107 1108 1109 1110
    ];

    await tester.pumpWidget(
      buildNavigator(
        pages: myPages,
1111 1112 1113 1114
        onPopPage: (Route<dynamic> route, dynamic result) {
          assert(false); // The test should never execute this.
          return true;
        },
1115
        transitionDelegate: detector,
1116
      ),
1117 1118 1119 1120 1121 1122 1123 1124
    );
    // There should be no transition because the page has the same key.
    expect(detector.hasTransition, isFalse);
    // Page one sets the maintain state to be true, its widget tree should be
    // built.
    expect(find.text('first', skipOffstage: false), findsOneWidget);
    expect(find.text('second'), findsOneWidget);
  });
1125 1126 1127 1128 1129 1130 1131

  testWidgets('MaterialPage does not lose its state when transitioning out', (WidgetTester tester) async {
    final GlobalKey<NavigatorState> navigator = GlobalKey<NavigatorState>();
    await tester.pumpWidget(KeepsStateTestWidget(navigatorKey: navigator));
    expect(find.text('subpage'), findsOneWidget);
    expect(find.text('home'), findsNothing);

1132
    navigator.currentState!.pop();
1133 1134 1135 1136 1137
    await tester.pump();

    expect(find.text('subpage'), findsOneWidget);
    expect(find.text('home'), findsOneWidget);
  });
1138 1139 1140 1141 1142

  testWidgets('MaterialPage restores its state', (WidgetTester tester) async {
    await tester.pumpWidget(
      RootRestorationScope(
        restorationId: 'root',
1143
        child: TestDependencies(
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
          child: Navigator(
            onPopPage: (Route<dynamic> route, dynamic result) { return false; },
            pages: const <Page<Object?>>[
              MaterialPage<void>(
                restorationId: 'p1',
                child: TestRestorableWidget(restorationId: 'p1'),
              ),
            ],
            restorationScopeId: 'nav',
            onGenerateRoute: (RouteSettings settings) {
              return MaterialPageRoute<void>(
                settings: settings,
                builder: (BuildContext context) {
                  return TestRestorableWidget(restorationId: settings.name!);
                },
              );
            },
          ),
        ),
      ),
    );

    expect(find.text('p1'), findsOneWidget);
    expect(find.text('count: 0'), findsOneWidget);

    await tester.tap(find.text('increment'));
    await tester.pump();
    expect(find.text('count: 1'), findsOneWidget);

    tester.state<NavigatorState>(find.byType(Navigator)).restorablePushNamed('p2');
    await tester.pumpAndSettle();

    expect(find.text('p1'), findsNothing);
    expect(find.text('p2'), findsOneWidget);

    await tester.tap(find.text('increment'));
    await tester.pump();
    await tester.tap(find.text('increment'));
    await tester.pump();
    expect(find.text('count: 2'), findsOneWidget);

    await tester.restartAndRestore();

    expect(find.text('p2'), findsOneWidget);
    expect(find.text('count: 2'), findsOneWidget);

    tester.state<NavigatorState>(find.byType(Navigator)).pop();
    await tester.pumpAndSettle();

    expect(find.text('p1'), findsOneWidget);
    expect(find.text('count: 1'), findsOneWidget);
  });
1196 1197 1198 1199 1200 1201
}

class TransitionDetector extends DefaultTransitionDelegate<void> {
  bool hasTransition = false;
  @override
  Iterable<RouteTransitionRecord> resolve({
1202 1203
    required List<RouteTransitionRecord> newPageRouteHistory,
    required Map<RouteTransitionRecord?, RouteTransitionRecord> locationToExitingPageRoute,
1204
    required Map<RouteTransitionRecord?, List<RouteTransitionRecord>> pageRouteToPagelessRoutes,
1205 1206 1207 1208 1209
  }) {
    hasTransition = true;
    return super.resolve(
      newPageRouteHistory: newPageRouteHistory,
      locationToExitingPageRoute: locationToExitingPageRoute,
1210
      pageRouteToPagelessRoutes: pageRouteToPagelessRoutes,
1211 1212 1213 1214 1215
    );
  }
}

Widget buildNavigator({
1216 1217 1218
  required List<Page<dynamic>> pages,
  required PopPageCallback onPopPage,
  GlobalKey<NavigatorState>? key,
1219
  TransitionDelegate<dynamic>? transitionDelegate,
1220 1221
}) {
  return MediaQuery(
1222
    data: MediaQueryData.fromView(WidgetsBinding.instance.window),
1223 1224 1225 1226
    child: Localizations(
      locale: const Locale('en', 'US'),
      delegates: const <LocalizationsDelegate<dynamic>>[
        DefaultMaterialLocalizations.delegate,
1227
        DefaultWidgetsLocalizations.delegate,
1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239
      ],
      child: Directionality(
        textDirection: TextDirection.ltr,
        child: Navigator(
          key: key,
          pages: pages,
          onPopPage: onPopPage,
          transitionDelegate: transitionDelegate ?? const DefaultTransitionDelegate<dynamic>(),
        ),
      ),
    ),
  );
1240
}
1241 1242

class KeepsStateTestWidget extends StatefulWidget {
1243
  const KeepsStateTestWidget({super.key, this.navigatorKey});
1244

1245
  final Key? navigatorKey;
1246 1247 1248 1249 1250 1251

  @override
  State<KeepsStateTestWidget> createState() => _KeepsStateTestWidgetState();
}

class _KeepsStateTestWidgetState extends State<KeepsStateTestWidget> {
1252
  String? _subpage = 'subpage';
1253 1254 1255 1256 1257 1258 1259 1260

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Navigator(
        key: widget.navigatorKey,
        pages: <Page<void>>[
          const MaterialPage<void>(child: Text('home')),
1261
          if (_subpage != null) MaterialPage<void>(child: Text(_subpage!)),
1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275
        ],
        onPopPage: (Route<dynamic> route, dynamic result) {
          if (!route.didPop(result)) {
            return false;
          }
          setState(() {
            _subpage = null;
          });
          return true;
        },
      ),
    );
  }
}
1276 1277

class TestRestorableWidget extends StatefulWidget {
1278
  const TestRestorableWidget({super.key, required this.restorationId});
1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314

  final String restorationId;

  @override
  State<StatefulWidget> createState() => _TestRestorableWidgetState();
}

class _TestRestorableWidgetState extends State<TestRestorableWidget> with RestorationMixin {
  @override
  String? get restorationId => widget.restorationId;

  final RestorableInt counter = RestorableInt(0);

  @override
  void restoreState(RestorationBucket? oldBucket, bool initialRestore) {
    registerForRestoration(counter, 'counter');
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        Text(widget.restorationId),
        Text('count: ${counter.value}'),
        ElevatedButton(
          onPressed: () {
            setState(() {
              counter.value++;
            });
          },
          child: const Text('increment'),
        ),
      ],
    );
  }
}
1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325

class TestDependencies extends StatelessWidget {
  const TestDependencies({required this.child, super.key});

  final Widget child;

  @override
  Widget build(BuildContext context) {
    return Directionality(
      textDirection: TextDirection.ltr,
      child: MediaQuery(
1326
        data: MediaQueryData.fromView(View.of(context)),
1327 1328 1329 1330 1331
        child: child,
      ),
    );
  }
}
1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349

class TestWindowPadding implements ui.WindowPadding {
  const TestWindowPadding({
    required this.left,
    required this.top,
    required this.right,
    required this.bottom,
  });

  @override
  final double left;
  @override
  final double top;
  @override
  final double right;
  @override
  final double bottom;
}