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

5 6
import 'dart:ui' as ui;

7
import 'package:flutter/foundation.dart';
8
import 'package:flutter/gestures.dart';
Adam Barth's avatar
Adam Barth committed
9
import 'package:flutter_test/flutter_test.dart';
10
import 'package:flutter/cupertino.dart';
11
import 'package:flutter/material.dart';
12
import 'package:flutter/rendering.dart';
13

14 15 16 17 18 19 20 21 22 23 24 25 26
import '../painting/image_test_utils.dart' show TestImageProvider;

Future<ui.Image> createTestImage() {
  final ui.Paint paint = ui.Paint()
    ..style = ui.PaintingStyle.stroke
    ..strokeWidth = 1.0;
  final ui.PictureRecorder recorder = ui.PictureRecorder();
  final ui.Canvas pictureCanvas = ui.Canvas(recorder);
  pictureCanvas.drawCircle(Offset.zero, 20.0, paint);
  final ui.Picture picture = recorder.endRecording();
  return picture.toImage(300, 300);
}

27 28 29
Key firstKey = const Key('first');
Key secondKey = const Key('second');
Key thirdKey = const Key('third');
30
Key simpleKey = const Key('simple');
31

32 33 34 35
Key homeRouteKey = const Key('homeRoute');
Key routeTwoKey = const Key('routeTwo');
Key routeThreeKey = const Key('routeThree');

xster's avatar
xster committed
36 37
bool transitionFromUserGestures = false;

38
final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{
39 40
  '/': (BuildContext context) => Material(
    child: ListView(
41
      key: homeRouteKey,
42
      children: <Widget>[
43
        Container(height: 100.0, width: 100.0),
xster's avatar
xster committed
44 45 46 47 48
        Card(child: Hero(
          tag: 'a',
          transitionOnUserGestures: transitionFromUserGestures,
          child: Container(height: 100.0, width: 100.0, key: firstKey),
        )),
49 50
        Container(height: 100.0, width: 100.0),
        FlatButton(
51
          child: const Text('two'),
52
          onPressed: () { Navigator.pushNamed(context, '/two'); },
53
        ),
54
        FlatButton(
55
          child: const Text('twoInset'),
56
          onPressed: () { Navigator.pushNamed(context, '/twoInset'); },
57
        ),
58 59 60 61
        FlatButton(
          child: const Text('simple'),
          onPressed: () { Navigator.pushNamed(context, '/simple'); },
        ),
62 63
      ],
    ),
64
  ),
65 66
  '/two': (BuildContext context) => Material(
    child: ListView(
67
      key: routeTwoKey,
68
      children: <Widget>[
69
        FlatButton(
70
          child: const Text('pop'),
71
          onPressed: () { Navigator.pop(context); },
72
        ),
73
        Container(height: 150.0, width: 150.0),
xster's avatar
xster committed
74 75 76 77 78
        Card(child: Hero(
          tag: 'a',
          transitionOnUserGestures: transitionFromUserGestures,
          child: Container(height: 150.0, width: 150.0, key: secondKey),
        )),
79 80
        Container(height: 150.0, width: 150.0),
        FlatButton(
81
          child: const Text('three'),
82
          onPressed: () { Navigator.push(context, ThreeRoute()); },
83
        ),
84 85
      ],
    ),
86
  ),
87 88 89 90
  // This route is the same as /two except that Hero 'a' is shifted to the right by
  // 50 pixels. When the hero's in-flight bounds between / and /twoInset are animated
  // using MaterialRectArcTween (the default) they'll follow a different path
  // then when the flight starts at /twoInset and returns to /.
91 92
  '/twoInset': (BuildContext context) => Material(
    child: ListView(
93 94
      key: routeTwoKey,
      children: <Widget>[
95
        FlatButton(
96
          child: const Text('pop'),
97
          onPressed: () { Navigator.pop(context); },
98
        ),
99 100 101
        Container(height: 150.0, width: 150.0),
        Card(
          child: Padding(
102
            padding: const EdgeInsets.only(left: 50.0),
xster's avatar
xster committed
103 104 105 106
            child: Hero(
              tag: 'a',
              transitionOnUserGestures: transitionFromUserGestures,
              child: Container(height: 150.0, width: 150.0, key: secondKey),
107
            ),
108 109
          ),
        ),
110 111
        Container(height: 150.0, width: 150.0),
        FlatButton(
112
          child: const Text('three'),
113
          onPressed: () { Navigator.push(context, ThreeRoute()); },
114
        ),
115 116
      ],
    ),
117
  ),
118 119 120 121 122 123 124 125 126 127 128 129 130
  // This route is the same as /two except that Hero 'a' is shifted to the right by
  // 50 pixels. When the hero's in-flight bounds between / and /twoInset are animated
  // using MaterialRectArcTween (the default) they'll follow a different path
  // then when the flight starts at /twoInset and returns to /.
  '/simple': (BuildContext context) => CupertinoPageScaffold(
    child: Center(
      child: Hero(
        tag: 'a',
        transitionOnUserGestures: transitionFromUserGestures,
        child: Container(height: 150.0, width: 150.0, key: simpleKey),
      ),
    ),
  ),
131
};
132

133
class ThreeRoute extends MaterialPageRoute<void> {
134 135 136 137 138 139 140 141 142 143 144 145 146
  ThreeRoute()
    : super(builder: (BuildContext context) {
        return Material(
          key: routeThreeKey,
          child: ListView(
            children: <Widget>[
              Container(height: 200.0, width: 200.0),
              Card(child: Hero(tag: 'a', child: Container(height: 200.0, width: 200.0, key: thirdKey))),
              Container(height: 200.0, width: 200.0),
            ],
          ),
        );
      });
147 148
}

149
class MutatingRoute extends MaterialPageRoute<void> {
150 151 152 153
  MutatingRoute()
    : super(builder: (BuildContext context) {
        return Hero(tag: 'a', child: const Text('MutatingRoute'), key: UniqueKey());
      });
154 155 156 157 158 159 160 161

  void markNeedsBuild() {
    setState(() {
      // Trigger a rebuild
    });
  }
}

162 163 164 165 166 167 168 169 170 171 172 173 174
class _SimpleStatefulWidget extends StatefulWidget {
  const _SimpleStatefulWidget({ Key key }) : super(key: key);
  @override
  _SimpleState createState() => _SimpleState();
}

class _SimpleState extends State<_SimpleStatefulWidget> {
  int state = 0;

  @override
  Widget build(BuildContext context) => Text(state.toString());
}

175
class MyStatefulWidget extends StatefulWidget {
176
  const MyStatefulWidget({ Key key, this.value = '123' }) : super(key: key);
177 178
  final String value;
  @override
179
  MyStatefulWidgetState createState() => MyStatefulWidgetState();
180 181 182 183
}

class MyStatefulWidgetState extends State<MyStatefulWidget> {
  @override
184
  Widget build(BuildContext context) => Text(widget.value);
185 186
}

187 188
Future<void> main() async {
  final ui.Image testImage = await createTestImage();
189
  assert(testImage != null);
190

xster's avatar
xster committed
191 192 193 194
  setUp(() {
    transitionFromUserGestures = false;
  });

195
  testWidgets('Heroes animate', (WidgetTester tester) async {
196

197
    await tester.pumpWidget(MaterialApp(routes: routes));
198

199
    // the initial setup.
200

201
    expect(find.byKey(firstKey), isOnstage);
202 203
    expect(find.byKey(firstKey), isInCard);
    expect(find.byKey(secondKey), findsNothing);
204

205 206
    await tester.tap(find.text('two'));
    await tester.pump(); // begin navigation
207

208
    // at this stage, the second route is offstage, so that we can form the
209
    // hero party.
210

211
    expect(find.byKey(firstKey), isOnstage);
212
    expect(find.byKey(firstKey), isInCard);
213 214
    expect(find.byKey(secondKey, skipOffstage: false), isOffstage);
    expect(find.byKey(secondKey, skipOffstage: false), isInCard);
215

216
    await tester.pump();
217

218 219
    // at this stage, the heroes have just gone on their journey, we are
    // seeing them at t=16ms. The original page no longer contains the hero.
220

221
    expect(find.byKey(firstKey), findsNothing);
222 223

    expect(find.byKey(secondKey), findsOneWidget);
224
    expect(find.byKey(secondKey), isNotInCard);
225
    expect(find.byKey(secondKey), isOnstage);
226

227
    await tester.pump();
228

229
    // t=32ms for the journey. Surely they are still at it.
230

231
    expect(find.byKey(firstKey), findsNothing);
232 233 234 235

    expect(find.byKey(secondKey), findsOneWidget);

    expect(find.byKey(secondKey), findsOneWidget);
236
    expect(find.byKey(secondKey), isNotInCard);
237
    expect(find.byKey(secondKey), isOnstage);
238

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

241
    // t=1.032s for the journey. The journey has ended (it ends this frame, in
242 243
    // fact). The hero should now be in the new page, onstage. The original
    // widget will be back as well now (though not visible).
244

245
    expect(find.byKey(firstKey), findsNothing);
246
    expect(find.byKey(secondKey), isOnstage);
247
    expect(find.byKey(secondKey), isInCard);
248

249
    await tester.pump();
250

251
    // Should not change anything.
252

253
    expect(find.byKey(firstKey), findsNothing);
254
    expect(find.byKey(secondKey), isOnstage);
255
    expect(find.byKey(secondKey), isInCard);
256

257
    // Now move on to view 3
258

259 260
    await tester.tap(find.text('three'));
    await tester.pump(); // begin navigation
261

262
    // at this stage, the second route is offstage, so that we can form the
263
    // hero party.
264

265
    expect(find.byKey(secondKey), isOnstage);
266
    expect(find.byKey(secondKey), isInCard);
267 268
    expect(find.byKey(thirdKey, skipOffstage: false), isOffstage);
    expect(find.byKey(thirdKey, skipOffstage: false), isInCard);
269

270
    await tester.pump();
271

272 273
    // at this stage, the heroes have just gone on their journey, we are
    // seeing them at t=16ms. The original page no longer contains the hero.
274

275
    expect(find.byKey(secondKey), findsNothing);
276
    expect(find.byKey(thirdKey), isOnstage);
277
    expect(find.byKey(thirdKey), isNotInCard);
278

279
    await tester.pump();
280

281
    // t=32ms for the journey. Surely they are still at it.
282

283
    expect(find.byKey(secondKey), findsNothing);
284
    expect(find.byKey(thirdKey), isOnstage);
285
    expect(find.byKey(thirdKey), isNotInCard);
286

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

289
    // t=1.032s for the journey. The journey has ended (it ends this frame, in
290
    // fact). The hero should now be in the new page, onstage.
291

292
    expect(find.byKey(secondKey), findsNothing);
293
    expect(find.byKey(thirdKey), isOnstage);
294
    expect(find.byKey(thirdKey), isInCard);
295

296
    await tester.pump();
297

298
    // Should not change anything.
299

300
    expect(find.byKey(secondKey), findsNothing);
301
    expect(find.byKey(thirdKey), isOnstage);
302
    expect(find.byKey(thirdKey), isInCard);
303
  });
304

305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
  testWidgets('Heroes animate should hide original hero', (WidgetTester tester) async {
    await tester.pumpWidget(MaterialApp(routes: routes));
    // Checks initial state.
    expect(find.byKey(firstKey), isOnstage);
    expect(find.byKey(firstKey), isInCard);
    expect(find.byKey(secondKey), findsNothing);

    await tester.tap(find.text('two'));
    await tester.pumpAndSettle(); // Waits for transition finishes.

    expect(find.byKey(firstKey), findsNothing);
    final Offstage first = tester.widget(
      find.ancestor(
        of: find.byKey(firstKey, skipOffstage: false),
        matching: find.byType(Offstage, skipOffstage: false),
320
      ).first,
321 322 323 324 325 326 327
    );
    // Original hero should stay hidden.
    expect(first.offstage, isTrue);
    expect(find.byKey(secondKey), isOnstage);
    expect(find.byKey(secondKey), isInCard);
  });

328
  testWidgets('Destination hero is rebuilt midflight', (WidgetTester tester) async {
329
    final MutatingRoute route = MutatingRoute();
330

331 332 333
    await tester.pumpWidget(MaterialApp(
      home: Material(
        child: ListView(
334
          children: <Widget>[
335
            const Hero(tag: 'a', child: Text('foo')),
336 337
            Builder(builder: (BuildContext context) {
              return FlatButton(child: const Text('two'), onPressed: () => Navigator.push(context, route));
338 339 340 341
            }),
          ],
        ),
      ),
342 343 344
    ));

    await tester.tap(find.text('two'));
345
    await tester.pump(const Duration(milliseconds: 10));
346 347 348

    route.markNeedsBuild();

349 350
    await tester.pump(const Duration(milliseconds: 10));
    await tester.pump(const Duration(seconds: 1));
351
  });
352

353
  testWidgets('Heroes animation is fastOutSlowIn', (WidgetTester tester) async {
354
    await tester.pumpWidget(MaterialApp(routes: routes));
355 356 357 358 359 360
    await tester.tap(find.text('two'));
    await tester.pump(); // begin navigation

    // Expect the height of the secondKey Hero to vary from 100 to 150
    // over duration and according to curve.

361
    const Duration duration = Duration(milliseconds: 300);
362
    const Curve curve = Curves.fastOutSlowIn;
363 364
    final double initialHeight = tester.getSize(find.byKey(firstKey, skipOffstage: false)).height;
    final double finalHeight = tester.getSize(find.byKey(secondKey, skipOffstage: false)).height;
365
    final double deltaHeight = finalHeight - initialHeight;
366
    const double epsilon = 0.001;
367 368 369 370

    await tester.pump(duration * 0.25);
    expect(
      tester.getSize(find.byKey(secondKey)).height,
371
      closeTo(curve.transform(0.25) * deltaHeight + initialHeight, epsilon),
372 373 374 375 376
    );

    await tester.pump(duration * 0.25);
    expect(
      tester.getSize(find.byKey(secondKey)).height,
377
      closeTo(curve.transform(0.50) * deltaHeight + initialHeight, epsilon),
378 379 380 381 382
    );

    await tester.pump(duration * 0.25);
    expect(
      tester.getSize(find.byKey(secondKey)).height,
383
      closeTo(curve.transform(0.75) * deltaHeight + initialHeight, epsilon),
384 385 386 387 388
    );

    await tester.pump(duration * 0.25);
    expect(
      tester.getSize(find.byKey(secondKey)).height,
389
      closeTo(curve.transform(1.0) * deltaHeight + initialHeight, epsilon),
390 391 392
    );
  });

393
  testWidgets('Heroes are not interactive', (WidgetTester tester) async {
394
    final List<String> log = <String>[];
395

396 397 398
    await tester.pumpWidget(MaterialApp(
      home: Center(
        child: Hero(
399
          tag: 'foo',
400
          child: GestureDetector(
401 402 403
            onTap: () {
              log.add('foo');
            },
404
            child: Container(
405 406
              width: 100.0,
              height: 100.0,
407 408 409 410
              child: const Text('foo'),
            ),
          ),
        ),
411 412 413
      ),
      routes: <String, WidgetBuilder>{
        '/next': (BuildContext context) {
414
          return Align(
415
            alignment: Alignment.topLeft,
416
            child: Hero(
417
              tag: 'foo',
418
              child: GestureDetector(
419 420 421
                onTap: () {
                  log.add('bar');
                },
422
                child: Container(
423 424
                  width: 100.0,
                  height: 150.0,
425 426 427 428
                  child: const Text('bar'),
                ),
              ),
            ),
429
          );
430 431
        },
      },
432 433 434 435 436 437 438
    ));

    expect(log, isEmpty);
    await tester.tap(find.text('foo'));
    expect(log, equals(<String>['foo']));
    log.clear();

439
    final NavigatorState navigator = tester.state(find.byType(Navigator));
440 441 442
    navigator.pushNamed('/next');

    expect(log, isEmpty);
443
    await tester.tap(find.text('foo', skipOffstage: false));
444 445
    expect(log, isEmpty);

446
    await tester.pump(const Duration(milliseconds: 10));
447
    await tester.tap(find.text('foo', skipOffstage: false));
448
    expect(log, isEmpty);
449
    await tester.tap(find.text('bar', skipOffstage: false));
450 451
    expect(log, isEmpty);

452
    await tester.pump(const Duration(milliseconds: 10));
453
    expect(find.text('foo'), findsNothing);
454
    await tester.tap(find.text('bar', skipOffstage: false));
455 456
    expect(log, isEmpty);

457
    await tester.pump(const Duration(seconds: 1));
458 459 460 461
    expect(find.text('foo'), findsNothing);
    await tester.tap(find.text('bar'));
    expect(log, equals(<String>['bar']));
  });
462 463

  testWidgets('Popping on first frame does not cause hero observer to crash', (WidgetTester tester) async {
464
    await tester.pumpWidget(MaterialApp(
465
      onGenerateRoute: (RouteSettings settings) {
466
        return MaterialPageRoute<void>(
467
          settings: settings,
468
          builder: (BuildContext context) => Hero(tag: 'test', child: Container()),
469 470 471 472 473
        );
      },
    ));
    await tester.pump();

474
    final Finder heroes = find.byType(Hero);
475 476 477 478 479 480 481 482 483 484
    expect(heroes, findsOneWidget);

    Navigator.pushNamed(heroes.evaluate().first, 'test');
    await tester.pump(); // adds the new page to the tree...

    Navigator.pop(heroes.evaluate().first);
    await tester.pump(); // ...and removes it straight away (since it's already at 0.0)
  });

  testWidgets('Overlapping starting and ending a hero transition works ok', (WidgetTester tester) async {
485
    await tester.pumpWidget(MaterialApp(
486
      onGenerateRoute: (RouteSettings settings) {
487
        return MaterialPageRoute<void>(
488
          settings: settings,
489
          builder: (BuildContext context) => Hero(tag: 'test', child: Container()),
490 491 492 493 494
        );
      },
    ));
    await tester.pump();

495
    final Finder heroes = find.byType(Hero);
496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511
    expect(heroes, findsOneWidget);

    Navigator.pushNamed(heroes.evaluate().first, 'test');
    await tester.pump();
    await tester.pump(const Duration(hours: 1));

    Navigator.pushNamed(heroes.evaluate().first, 'test');
    await tester.pump();
    await tester.pump(const Duration(hours: 1));

    Navigator.pop(heroes.evaluate().first);
    await tester.pump();
    Navigator.pop(heroes.evaluate().first);
    await tester.pump(const Duration(hours: 1)); // so the first transition is finished, but the second hasn't started
    await tester.pump();
  });
Hans Muller's avatar
Hans Muller committed
512 513

  testWidgets('One route, two heroes, same tag, throws', (WidgetTester tester) async {
514 515 516
    await tester.pumpWidget(MaterialApp(
      home: Material(
        child: ListView(
Hans Muller's avatar
Hans Muller committed
517
          children: <Widget>[
518 519
            const Hero(tag: 'a', child: Text('a')),
            const Hero(tag: 'a', child: Text('a too')),
520
            Builder(
Hans Muller's avatar
Hans Muller committed
521
              builder: (BuildContext context) {
522
                return FlatButton(
523
                  child: const Text('push'),
Hans Muller's avatar
Hans Muller committed
524
                  onPressed: () {
525
                    Navigator.push(context, PageRouteBuilder<void>(
Hans Muller's avatar
Hans Muller committed
526
                      pageBuilder: (BuildContext context, Animation<double> _, Animation<double> __) {
527
                        return const Text('fail');
Hans Muller's avatar
Hans Muller committed
528 529 530 531 532 533 534 535 536 537 538 539 540
                      },
                    ));
                  },
                );
              },
            ),
          ],
        ),
      ),
    ));

    await tester.tap(find.text('push'));
    await tester.pump();
541 542
    final dynamic exception = tester.takeException();
    expect(exception, isFlutterError);
543
    final FlutterError error = exception as FlutterError;
544 545
    expect(error.diagnostics.length, 3);
    final DiagnosticsNode last = error.diagnostics.last;
Dan Field's avatar
Dan Field committed
546
    expect(last, isA<DiagnosticsProperty<StatefulElement>>());
547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565
    expect(
      last.toStringDeep(),
      equalsIgnoringHashCodes(
        '# Here is the subtree for one of the offending heroes: Hero\n',
      ),
    );
    expect(last.style, DiagnosticsTreeStyle.dense);
    expect(
      error.toStringDeep(),
      equalsIgnoringHashCodes(
        'FlutterError\n'
        '   There are multiple heroes that share the same tag within a\n'
        '   subtree.\n'
        '   Within each subtree for which heroes are to be animated (i.e. a\n'
        '   PageRoute subtree), each Hero must have a unique non-null tag.\n'
        '   In this case, multiple heroes had the following tag: a\n'
        '   ├# Here is the subtree for one of the offending heroes: Hero\n',
      ),
    );
Hans Muller's avatar
Hans Muller committed
566 567
  });

568
  testWidgets('Hero push transition interrupted by a pop', (WidgetTester tester) async {
569
    await tester.pumpWidget(MaterialApp(
570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621
      routes: routes
    ));

    // Initially the firstKey Card on the '/' route is visible
    expect(find.byKey(firstKey), isOnstage);
    expect(find.byKey(firstKey), isInCard);
    expect(find.byKey(secondKey), findsNothing);

    // Pushes MaterialPageRoute '/two'.
    await tester.tap(find.text('two'));

    // Start the flight of Hero 'a' from route '/' to route '/two'. Route '/two'
    // is now offstage.
    await tester.pump();

    final double initialHeight = tester.getSize(find.byKey(firstKey)).height;
    final double finalHeight = tester.getSize(find.byKey(secondKey, skipOffstage: false)).height;
    expect(finalHeight, greaterThan(initialHeight)); // simplify the checks below

    // Build the first hero animation frame in the navigator's overlay.
    await tester.pump();

    // At this point the hero widgets have been replaced by placeholders
    // and the destination hero has been moved to the overlay.
    expect(find.descendant(of: find.byKey(homeRouteKey), matching: find.byKey(firstKey)), findsNothing);
    expect(find.descendant(of: find.byKey(routeTwoKey), matching: find.byKey(secondKey)), findsNothing);
    expect(find.byKey(firstKey), findsNothing);
    expect(find.byKey(secondKey), isOnstage);

    // The duration of a MaterialPageRoute's transition is 300ms.
    // At 150ms Hero 'a' is mid-flight.
    await tester.pump(const Duration(milliseconds: 150));
    final double height150ms = tester.getSize(find.byKey(secondKey)).height;
    expect(height150ms, greaterThan(initialHeight));
    expect(height150ms, lessThan(finalHeight));

    // Pop route '/two' before the push transition to '/two' has finished.
    await tester.tap(find.text('pop'));

    // Restart the flight of Hero 'a'. Now it's flying from route '/two' to
    // route '/'.
    await tester.pump();

    // After flying in the opposite direction for 50ms Hero 'a' will
    // be smaller than it was, but bigger than its initial size.
    await tester.pump(const Duration(milliseconds: 50));
    final double height100ms = tester.getSize(find.byKey(secondKey)).height;
    expect(height100ms, lessThan(height150ms));
    expect(finalHeight, greaterThan(height100ms));

    // Hero a's return flight at 149ms. The outgoing (push) flight took
    // 150ms so we should be just about back to where Hero 'a' started.
622
    const double epsilon = 0.001;
623 624 625 626 627 628 629 630 631 632 633 634
    await tester.pump(const Duration(milliseconds: 99));
    closeTo(tester.getSize(find.byKey(secondKey)).height - initialHeight, epsilon);

    // The flight is finished. We're back to where we started.
    await tester.pump(const Duration(milliseconds: 300));
    expect(find.byKey(firstKey), isOnstage);
    expect(find.byKey(firstKey), isInCard);
    expect(find.byKey(secondKey), findsNothing);
  });

  testWidgets('Hero pop transition interrupted by a push', (WidgetTester tester) async {
    await tester.pumpWidget(
635
      MaterialApp(routes: routes)
636 637 638 639 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 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685
    );

    // Pushes MaterialPageRoute '/two'.
    await tester.tap(find.text('two'));
    await tester.pump();
    await tester.pump(const Duration(seconds: 1));

    // Now the secondKey Card on the '/2' route is visible
    expect(find.byKey(secondKey), isOnstage);
    expect(find.byKey(secondKey), isInCard);
    expect(find.byKey(firstKey), findsNothing);

    // Pop MaterialPageRoute '/two'.
    await tester.tap(find.text('pop'));

    // Start the flight of Hero 'a' from route '/two' to route '/'. Route '/two'
    // is now offstage.
    await tester.pump();

    final double initialHeight = tester.getSize(find.byKey(secondKey)).height;
    final double finalHeight = tester.getSize(find.byKey(firstKey, skipOffstage: false)).height;
    expect(finalHeight, lessThan(initialHeight)); // simplify the checks below

    // Build the first hero animation frame in the navigator's overlay.
    await tester.pump();

    // At this point the hero widgets have been replaced by placeholders
    // and the destination hero has been moved to the overlay.
    expect(find.descendant(of: find.byKey(homeRouteKey), matching: find.byKey(firstKey)), findsNothing);
    expect(find.descendant(of: find.byKey(routeTwoKey), matching: find.byKey(secondKey)), findsNothing);
    expect(find.byKey(firstKey), isOnstage);
    expect(find.byKey(secondKey), findsNothing);

    // The duration of a MaterialPageRoute's transition is 300ms.
    // At 150ms Hero 'a' is mid-flight.
    await tester.pump(const Duration(milliseconds: 150));
    final double height150ms = tester.getSize(find.byKey(firstKey)).height;
    expect(height150ms, lessThan(initialHeight));
    expect(height150ms, greaterThan(finalHeight));

    // Push route '/two' before the pop transition from '/two' has finished.
    await tester.tap(find.text('two'));

    // Restart the flight of Hero 'a'. Now it's flying from route '/' to
    // route '/two'.
    await tester.pump();

    // After flying in the opposite direction for 50ms Hero 'a' will
    // be smaller than it was, but bigger than its initial size.
    await tester.pump(const Duration(milliseconds: 50));
686 687 688
    final double height200ms = tester.getSize(find.byKey(firstKey)).height;
    expect(height200ms, greaterThan(height150ms));
    expect(finalHeight, lessThan(height200ms));
689 690 691

    // Hero a's return flight at 149ms. The outgoing (push) flight took
    // 150ms so we should be just about back to where Hero 'a' started.
692
    const double epsilon = 0.001;
693 694 695 696 697 698 699 700 701
    await tester.pump(const Duration(milliseconds: 99));
    closeTo(tester.getSize(find.byKey(firstKey)).height - initialHeight, epsilon);

    // The flight is finished. We're back to where we started.
    await tester.pump(const Duration(milliseconds: 300));
    expect(find.byKey(secondKey), isOnstage);
    expect(find.byKey(secondKey), isInCard);
    expect(find.byKey(firstKey), findsNothing);
  });
702 703

  testWidgets('Destination hero disappears mid-flight', (WidgetTester tester) async {
704 705
    const Key homeHeroKey = Key('home hero');
    const Key routeHeroKey = Key('route hero');
706 707 708 709
    bool routeIncludesHero = true;
    StateSetter heroCardSetState;

    // Show a 200x200 Hero tagged 'H', with key routeHeroKey
710
    final MaterialPageRoute<void> route = MaterialPageRoute<void>(
711
      builder: (BuildContext context) {
712 713
        return Material(
          child: ListView(
714
            children: <Widget>[
715
              StatefulBuilder(
716 717
                builder: (BuildContext context, StateSetter setState) {
                  heroCardSetState = setState;
718
                  return Card(
719
                    child: routeIncludesHero
720 721
                      ? Hero(tag: 'H', child: Container(key: routeHeroKey, height: 200.0, width: 200.0))
                      : Container(height: 200.0, width: 200.0),
722 723 724
                  );
                },
              ),
725
              FlatButton(
726
                child: const Text('POP'),
727
                onPressed: () { Navigator.pop(context); },
728 729
              ),
            ],
730
          ),
731 732 733 734 735 736
        );
      },
    );

    // Show a 100x100 Hero tagged 'H' with key homeHeroKey
    await tester.pumpWidget(
737 738 739
      MaterialApp(
        home: Scaffold(
          body: Builder(
740
            builder: (BuildContext context) { // Navigator.push() needs context
741
              return ListView(
742
                children: <Widget> [
743 744
                  Card(
                    child: Hero(tag: 'H', child: Container(key: homeHeroKey, height: 100.0, width: 100.0)),
745
                  ),
746
                  FlatButton(
747
                    child: const Text('PUSH'),
748
                    onPressed: () { Navigator.push(context, route); },
749 750 751 752 753 754
                  ),
                ],
              );
            },
          ),
        ),
755
      ),
756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793
    );

    // Pushes route
    await tester.tap(find.text('PUSH'));
    await tester.pump();
    await tester.pump();
    final double initialHeight = tester.getSize(find.byKey(routeHeroKey)).height;

    await tester.pump(const Duration(milliseconds: 10));
    double midflightHeight = tester.getSize(find.byKey(routeHeroKey)).height;
    expect(midflightHeight, greaterThan(initialHeight));
    expect(midflightHeight, lessThan(200.0));

    await tester.pump(const Duration(milliseconds: 300));
    await tester.pump();
    double finalHeight = tester.getSize(find.byKey(routeHeroKey)).height;
    expect(finalHeight, 200.0);

    // Complete the flight
    await tester.pump(const Duration(milliseconds: 100));

    // Rebuild route with its Hero

    heroCardSetState(() {
      routeIncludesHero = true;
    });
    await tester.pump();

    // Pops route
    await tester.tap(find.text('POP'));
    await tester.pump();
    await tester.pump();

    await tester.pump(const Duration(milliseconds: 10));
    midflightHeight = tester.getSize(find.byKey(homeHeroKey)).height;
    expect(midflightHeight, lessThan(finalHeight));
    expect(midflightHeight, greaterThan(100.0));

Josh Soref's avatar
Josh Soref committed
794
    // Remove the destination hero midflight
795 796 797 798 799 800 801 802 803 804
    heroCardSetState(() {
      routeIncludesHero = false;
    });
    await tester.pump();

    await tester.pump(const Duration(milliseconds: 300));
    finalHeight = tester.getSize(find.byKey(homeHeroKey)).height;
    expect(finalHeight, 100.0);

  });
805 806

  testWidgets('Destination hero scrolls mid-flight', (WidgetTester tester) async {
807 808 809
    const Key homeHeroKey = Key('home hero');
    const Key routeHeroKey = Key('route hero');
    const Key routeContainerKey = Key('route hero container');
810 811

    // Show a 200x200 Hero tagged 'H', with key routeHeroKey
812
    final MaterialPageRoute<void> route = MaterialPageRoute<void>(
813
      builder: (BuildContext context) {
814 815
        return Material(
          child: ListView(
816
            children: <Widget>[
817
              const SizedBox(height: 100.0),
818
              // This container will appear at Y=100
819
              Container(
820
                key: routeContainerKey,
821
                child: Hero(tag: 'H', child: Container(key: routeHeroKey, height: 200.0, width: 200.0)),
822
              ),
823
              FlatButton(
824
                child: const Text('POP'),
825
                onPressed: () { Navigator.pop(context); },
826
              ),
827
              const SizedBox(height: 600.0),
828
            ],
829
          ),
830 831 832 833 834 835
        );
      },
    );

    // Show a 100x100 Hero tagged 'H' with key homeHeroKey
    await tester.pumpWidget(
836 837 838
      MaterialApp(
        home: Scaffold(
          body: Builder(
839
            builder: (BuildContext context) { // Navigator.push() needs context
840
              return ListView(
841
                children: <Widget> [
842
                  const SizedBox(height: 200.0),
843
                  // This container will appear at Y=200
844 845
                  Container(
                    child: Hero(tag: 'H', child: Container(key: homeHeroKey, height: 100.0, width: 100.0)),
846
                  ),
847
                  FlatButton(
848
                    child: const Text('PUSH'),
849
                    onPressed: () { Navigator.push(context, route); },
850
                  ),
851
                  const SizedBox(height: 600.0),
852 853 854 855 856
                ],
              );
            },
          ),
        ),
857
      ),
858 859 860 861 862 863 864
    );

    // Pushes route
    await tester.tap(find.text('PUSH'));
    await tester.pump();
    await tester.pump();

865
    final double initialY = tester.getTopLeft(find.byKey(routeHeroKey)).dy;
866 867 868
    expect(initialY, 200.0);

    await tester.pump(const Duration(milliseconds: 100));
869
    final double yAt100ms = tester.getTopLeft(find.byKey(routeHeroKey)).dy;
870 871 872 873 874
    expect(yAt100ms, lessThan(200.0));
    expect(yAt100ms, greaterThan(100.0));

    // Scroll the target upwards by 25 pixels. The Hero flight's Y coordinate
    // will be redirected from 100 to 75.
875
    await tester.drag(find.byKey(routeContainerKey), const Offset(0.0, -25.0));
876 877
    await tester.pump();
    await tester.pump(const Duration(milliseconds: 10));
878
    final double yAt110ms = tester.getTopLeft(find.byKey(routeHeroKey)).dy;
879 880 881 882 883
    expect(yAt110ms, lessThan(yAt100ms));
    expect(yAt110ms, greaterThan(75.0));

    await tester.pump(const Duration(milliseconds: 300));
    await tester.pump();
884
    final double finalHeroY = tester.getTopLeft(find.byKey(routeHeroKey)).dy;
885 886 887 888
    expect(finalHeroY, 75.0); // 100 less 25 for the scroll
  });

  testWidgets('Destination hero scrolls out of view mid-flight', (WidgetTester tester) async {
889 890 891
    const Key homeHeroKey = Key('home hero');
    const Key routeHeroKey = Key('route hero');
    const Key routeContainerKey = Key('route hero container');
892 893

    // Show a 200x200 Hero tagged 'H', with key routeHeroKey
894
    final MaterialPageRoute<void> route = MaterialPageRoute<void>(
895
      builder: (BuildContext context) {
896 897
        return Material(
          child: ListView(
898
            cacheExtent: 0.0,
899
            children: <Widget>[
900
              const SizedBox(height: 100.0),
901
              // This container will appear at Y=100
902
              Container(
903
                key: routeContainerKey,
904
                child: Hero(tag: 'H', child: Container(key: routeHeroKey, height: 200.0, width: 200.0)),
905
              ),
906
              const SizedBox(height: 800.0),
907
            ],
908
          ),
909 910 911 912 913 914
        );
      },
    );

    // Show a 100x100 Hero tagged 'H' with key homeHeroKey
    await tester.pumpWidget(
915 916 917
      MaterialApp(
        home: Scaffold(
          body: Builder(
918
            builder: (BuildContext context) { // Navigator.push() needs context
919
              return ListView(
920
                children: <Widget> [
921
                  const SizedBox(height: 200.0),
922
                  // This container will appear at Y=200
923 924
                  Container(
                    child: Hero(tag: 'H', child: Container(key: homeHeroKey, height: 100.0, width: 100.0)),
925
                  ),
926
                  FlatButton(
927
                    child: const Text('PUSH'),
928
                    onPressed: () { Navigator.push(context, route); },
929 930 931 932 933 934
                  ),
                ],
              );
            },
          ),
        ),
935
      ),
936 937 938 939 940 941 942
    );

    // Pushes route
    await tester.tap(find.text('PUSH'));
    await tester.pump();
    await tester.pump();

943
    final double initialY = tester.getTopLeft(find.byKey(routeHeroKey)).dy;
944 945 946
    expect(initialY, 200.0);

    await tester.pump(const Duration(milliseconds: 100));
947
    final double yAt100ms = tester.getTopLeft(find.byKey(routeHeroKey)).dy;
948 949 950
    expect(yAt100ms, lessThan(200.0));
    expect(yAt100ms, greaterThan(100.0));

951
    await tester.drag(find.byKey(routeContainerKey), const Offset(0.0, -400.0));
952 953 954 955 956 957
    await tester.pump();
    await tester.pump(const Duration(milliseconds: 10));
    expect(find.byKey(routeContainerKey), findsNothing); // Scrolled off the top

    // Flight continues (the hero will fade out) even though the destination
    // no longer exists.
958
    final double yAt110ms = tester.getTopLeft(find.byKey(routeHeroKey)).dy;
959 960 961 962 963 964 965 966
    expect(yAt110ms, lessThan(yAt100ms));
    expect(yAt110ms, greaterThan(100.0));

    await tester.pump(const Duration(milliseconds: 300));
    await tester.pump();
    expect(find.byKey(routeHeroKey), findsNothing);
  });

967 968
  testWidgets('Aborted flight', (WidgetTester tester) async {
    // See https://github.com/flutter/flutter/issues/5798
969 970
    const Key heroABKey = Key('AB hero');
    const Key heroBCKey = Key('BC hero');
971 972

    // Show a 150x150 Hero tagged 'BC'
973
    final MaterialPageRoute<void> routeC = MaterialPageRoute<void>(
974
      builder: (BuildContext context) {
975 976
        return Material(
          child: ListView(
977 978
            children: <Widget>[
              // This container will appear at Y=0
979
              Container(
980 981 982 983 984 985
                child: Hero(
                  tag: 'BC',
                  child: Container(
                    key: heroBCKey,
                    height: 150.0,
                    child: const Text('Hero'),
986
                  ),
987
                ),
988
              ),
989
              const SizedBox(height: 800.0),
990
            ],
991
          ),
992 993 994 995 996
        );
      },
    );

    // Show a height=200 Hero tagged 'AB' and a height=50 Hero tagged 'BC'
997
    final MaterialPageRoute<void> routeB = MaterialPageRoute<void>(
998
      builder: (BuildContext context) {
999 1000
        return Material(
          child: ListView(
1001
            children: <Widget>[
1002
              const SizedBox(height: 100.0),
1003
              // This container will appear at Y=100
1004
              Container(
1005 1006 1007 1008 1009 1010
                child: Hero(
                  tag: 'AB',
                  child: Container(
                    key: heroABKey,
                    height: 200.0,
                    child: const Text('Hero'),
1011
                  ),
1012
                ),
1013
              ),
1014
              FlatButton(
1015
                child: const Text('PUSH C'),
1016
                onPressed: () { Navigator.push(context, routeC); },
1017
              ),
1018
              Container(
1019 1020 1021 1022 1023
                child: Hero(
                  tag: 'BC',
                  child: Container(
                    height: 150.0,
                    child: const Text('Hero'),
1024
                  ),
1025
                ),
1026
              ),
1027
              const SizedBox(height: 800.0),
1028
            ],
1029
          ),
1030 1031 1032 1033 1034 1035
        );
      },
    );

    // Show a 100x100 Hero tagged 'AB' with key heroABKey
    await tester.pumpWidget(
1036 1037 1038
      MaterialApp(
        home: Scaffold(
          body: Builder(
1039
            builder: (BuildContext context) { // Navigator.push() needs context
1040
              return ListView(
1041
                children: <Widget> [
1042
                  const SizedBox(height: 200.0),
1043
                  // This container will appear at Y=200
1044
                  Container(
1045 1046 1047 1048 1049 1050
                    child: Hero(
                      tag: 'AB',
                      child: Container(
                        height: 100.0,
                        width: 100.0,
                        child: const Text('Hero'),
1051
                      ),
1052
                    ),
1053
                  ),
1054
                  FlatButton(
1055
                    child: const Text('PUSH B'),
1056
                    onPressed: () { Navigator.push(context, routeB); },
1057 1058 1059 1060 1061 1062
                  ),
                ],
              );
            },
          ),
        ),
1063
      ),
1064 1065 1066 1067 1068 1069 1070
    );

    // Pushes routeB
    await tester.tap(find.text('PUSH B'));
    await tester.pump();
    await tester.pump();

1071
    final double initialY = tester.getTopLeft(find.byKey(heroABKey)).dy;
1072 1073 1074
    expect(initialY, 200.0);

    await tester.pump(const Duration(milliseconds: 200));
1075
    final double yAt200ms = tester.getTopLeft(find.byKey(heroABKey)).dy;
1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087
    // Hero AB is mid flight.
    expect(yAt200ms, lessThan(200.0));
    expect(yAt200ms, greaterThan(100.0));

    // Pushes route C, causes hero AB's flight to abort, hero BC's flight to start
    await tester.tap(find.text('PUSH C'));
    await tester.pump();
    await tester.pump();

    // Hero AB's aborted flight finishes where it was expected although
    // it's been faded out.
    await tester.pump(const Duration(milliseconds: 100));
1088
    expect(tester.getTopLeft(find.byKey(heroABKey)).dy, 100.0);
1089

1090 1091 1092
    bool _isVisible(Element node) {
      bool isVisible = true;
      node.visitAncestorElements((Element ancestor) {
1093 1094 1095 1096 1097 1098
        final RenderObject r = ancestor.renderObject;
        if (r is RenderOpacity && r.opacity == 0) {
          isVisible = false;
          return false;
        }
        return true;
1099 1100 1101 1102 1103 1104 1105
      });
      return isVisible;
    }

    // Of all heroes only one should be visible now.
    final Iterable<Element> elements = find.text('Hero').evaluate();
    expect(elements.where(_isVisible).length, 1);
1106 1107 1108

    // Hero BC's flight finishes normally.
    await tester.pump(const Duration(milliseconds: 300));
1109
    expect(tester.getTopLeft(find.byKey(heroBCKey)).dy, 0.0);
1110 1111
  });

1112
  testWidgets('Stateful hero child state survives flight', (WidgetTester tester) async {
1113
    final MaterialPageRoute<void> route = MaterialPageRoute<void>(
1114
      builder: (BuildContext context) {
1115 1116
        return Material(
          child: ListView(
1117
            children: <Widget>[
1118
              const Card(
1119
                child: Hero(
1120
                  tag: 'H',
1121
                  child: SizedBox(
1122
                    height: 200.0,
1123
                    child: MyStatefulWidget(value: '456'),
1124 1125 1126
                  ),
                ),
              ),
1127
              FlatButton(
1128
                child: const Text('POP'),
1129
                onPressed: () { Navigator.pop(context); },
1130 1131
              ),
            ],
1132
          ),
1133 1134 1135 1136 1137
        );
      },
    );

    await tester.pumpWidget(
1138 1139 1140
      MaterialApp(
        home: Scaffold(
          body: Builder(
1141
            builder: (BuildContext context) { // Navigator.push() needs context
1142
              return ListView(
1143
                children: <Widget> [
1144
                  const Card(
1145
                    child: Hero(
1146
                      tag: 'H',
1147
                      child: SizedBox(
1148
                        height: 100.0,
1149
                        child: MyStatefulWidget(value: '456'),
1150 1151 1152
                      ),
                    ),
                  ),
1153
                  FlatButton(
1154
                    child: const Text('PUSH'),
1155
                    onPressed: () { Navigator.push(context, route); },
1156 1157 1158 1159 1160 1161
                  ),
                ],
              );
            },
          ),
        ),
1162
      ),
1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173
    );

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

    // Push route.
    await tester.tap(find.text('PUSH'));
    await tester.pump();
    await tester.pump();

    // Push flight underway.
    await tester.pump(const Duration(milliseconds: 100));
1174
    // Visible in the hero animation.
1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194
    expect(find.text('456'), findsOneWidget);

    // Push flight finished.
    await tester.pump(const Duration(milliseconds: 300));
    expect(find.text('456'), findsOneWidget);

    // Pop route.
    await tester.tap(find.text('POP'));
    await tester.pump();
    await tester.pump();

    // Pop flight underway.
    await tester.pump(const Duration(milliseconds: 100));
    expect(find.text('456'), findsOneWidget);

    // Pop flight finished
    await tester.pump(const Duration(milliseconds: 300));
    expect(find.text('456'), findsOneWidget);

  });
1195 1196 1197

  testWidgets('Hero createRectTween', (WidgetTester tester) async {
    RectTween createRectTween(Rect begin, Rect end) {
1198
      return MaterialRectCenterArcTween(begin: begin, end: end);
1199 1200 1201
    }

    final Map<String, WidgetBuilder> createRectTweenHeroRoutes = <String, WidgetBuilder>{
1202 1203
      '/': (BuildContext context) => Material(
        child: Column(
1204 1205
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
1206
            Hero(
1207 1208
              tag: 'a',
              createRectTween: createRectTween,
1209
              child: Container(height: 100.0, width: 100.0, key: firstKey),
1210
            ),
1211
            FlatButton(
1212
              child: const Text('two'),
1213
              onPressed: () { Navigator.pushNamed(context, '/two'); },
1214
            ),
1215 1216
          ],
        ),
1217
      ),
1218 1219
      '/two': (BuildContext context) => Material(
        child: Column(
1220 1221
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
1222
            SizedBox(
1223
              height: 200.0,
1224
              child: FlatButton(
1225
                child: const Text('pop'),
1226
                onPressed: () { Navigator.pop(context); },
1227 1228
              ),
            ),
1229
            Hero(
1230 1231
              tag: 'a',
              createRectTween: createRectTween,
1232
              child: Container(height: 200.0, width: 100.0, key: secondKey),
1233 1234 1235 1236 1237 1238
            ),
          ],
        ),
      ),
    };

1239
    await tester.pumpWidget(MaterialApp(routes: createRectTweenHeroRoutes));
1240 1241
    expect(tester.getCenter(find.byKey(firstKey)), const Offset(50.0, 50.0));

1242
    const double epsilon = 0.001;
1243
    const Duration duration = Duration(milliseconds: 300);
1244
    const Curve curve = Curves.fastOutSlowIn;
1245
    final MaterialPointArcTween pushCenterTween = MaterialPointArcTween(
1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261
      begin: const Offset(50.0, 50.0),
      end: const Offset(400.0, 300.0),
    );

    await tester.tap(find.text('two'));
    await tester.pump(); // begin navigation

    // Verify that the center of the secondKey Hero flies along the
    // pushCenterTween arc for the push /two flight.

    await tester.pump();
    expect(tester.getCenter(find.byKey(secondKey)), const Offset(50.0, 50.0));

    await tester.pump(duration * 0.25);
    Offset actualHeroCenter = tester.getCenter(find.byKey(secondKey));
    Offset predictedHeroCenter = pushCenterTween.lerp(curve.transform(0.25));
1262
    expect(actualHeroCenter, within<Offset>(distance: epsilon, from: predictedHeroCenter));
1263 1264 1265 1266

    await tester.pump(duration * 0.25);
    actualHeroCenter = tester.getCenter(find.byKey(secondKey));
    predictedHeroCenter = pushCenterTween.lerp(curve.transform(0.5));
1267
    expect(actualHeroCenter, within<Offset>(distance: epsilon, from: predictedHeroCenter));
1268 1269 1270 1271

    await tester.pump(duration * 0.25);
    actualHeroCenter = tester.getCenter(find.byKey(secondKey));
    predictedHeroCenter = pushCenterTween.lerp(curve.transform(0.75));
1272
    expect(actualHeroCenter, within<Offset>(distance: epsilon, from: predictedHeroCenter));
1273 1274 1275 1276 1277 1278 1279 1280 1281 1282

    await tester.pumpAndSettle();
    expect(tester.getCenter(find.byKey(secondKey)), const Offset(400.0, 300.0));

    // Verify that the center of the firstKey Hero flies along the
    // pushCenterTween arc for the pop /two flight.

    await tester.tap(find.text('pop'));
    await tester.pump(); // begin navigation

1283
    final MaterialPointArcTween popCenterTween = MaterialPointArcTween(
1284 1285 1286 1287 1288 1289 1290 1291
      begin: const Offset(400.0, 300.0),
      end: const Offset(50.0, 50.0),
    );
    await tester.pump();
    expect(tester.getCenter(find.byKey(firstKey)), const Offset(400.0, 300.0));

    await tester.pump(duration * 0.25);
    actualHeroCenter = tester.getCenter(find.byKey(firstKey));
1292
    predictedHeroCenter = popCenterTween.lerp(curve.transform(0.25));
1293
    expect(actualHeroCenter, within<Offset>(distance: epsilon, from: predictedHeroCenter));
1294 1295 1296

    await tester.pump(duration * 0.25);
    actualHeroCenter = tester.getCenter(find.byKey(firstKey));
1297
    predictedHeroCenter = popCenterTween.lerp(curve.transform(0.5));
1298
    expect(actualHeroCenter, within<Offset>(distance: epsilon, from: predictedHeroCenter));
1299 1300 1301

    await tester.pump(duration * 0.25);
    actualHeroCenter = tester.getCenter(find.byKey(firstKey));
1302
    predictedHeroCenter = popCenterTween.lerp(curve.transform(0.75));
1303
    expect(actualHeroCenter, within<Offset>(distance: epsilon, from: predictedHeroCenter));
1304 1305 1306 1307 1308

    await tester.pumpAndSettle();
    expect(tester.getCenter(find.byKey(firstKey)), const Offset(50.0, 50.0));
  });

1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366
  testWidgets('Hero createRectTween for Navigator that is not full screen', (WidgetTester tester) async {
    // Regression test for https://github.com/flutter/flutter/issues/25272

    RectTween createRectTween(Rect begin, Rect end) {
      return RectTween(begin: begin, end: end);
    }

    final Map<String, WidgetBuilder> createRectTweenHeroRoutes = <String, WidgetBuilder>{
      '/': (BuildContext context) => Material(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Hero(
              tag: 'a',
              createRectTween: createRectTween,
              child: Container(height: 100.0, width: 100.0, key: firstKey),
            ),
            FlatButton(
              child: const Text('two'),
              onPressed: () { Navigator.pushNamed(context, '/two'); },
            ),
          ],
        ),
      ),
      '/two': (BuildContext context) => Material(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            SizedBox(
              height: 200.0,
              child: FlatButton(
                child: const Text('pop'),
                onPressed: () { Navigator.pop(context); },
              ),
            ),
            Hero(
              tag: 'a',
              createRectTween: createRectTween,
              child: Container(height: 200.0, width: 100.0, key: secondKey),
            ),
          ],
        ),
      ),
    };

    const double leftPadding = 10.0;

    // MaterialApp and its Navigator are offset from the left
    await tester.pumpWidget(Padding(
      padding: const EdgeInsets.only(left: leftPadding),
      child: MaterialApp(routes: createRectTweenHeroRoutes),
    ));
    expect(tester.getCenter(find.byKey(firstKey)), const Offset(leftPadding + 50.0, 50.0));

    const double epsilon = 0.001;
    const Duration duration = Duration(milliseconds: 300);
    const Curve curve = Curves.fastOutSlowIn;
    final RectTween pushRectTween = RectTween(
Dan Field's avatar
Dan Field committed
1367 1368
      begin: const Rect.fromLTWH(leftPadding, 0.0, 100.0, 100.0),
      end: const Rect.fromLTWH(350.0 + leftPadding / 2, 200.0, 100.0, 200.0),
1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404
    );

    await tester.tap(find.text('two'));
    await tester.pump(); // begin navigation

    // Verify that the rect of the secondKey Hero transforms as the
    // pushRectTween rect for the push /two flight.

    await tester.pump();
    expect(tester.getCenter(find.byKey(secondKey)), const Offset(50.0 + leftPadding, 50.0));

    await tester.pump(duration * 0.25);
    Rect actualHeroRect = tester.getRect(find.byKey(secondKey));
    Rect predictedHeroRect = pushRectTween.lerp(curve.transform(0.25));
    expect(actualHeroRect, within<Rect>(distance: epsilon, from: predictedHeroRect));

    await tester.pump(duration * 0.25);
    actualHeroRect = tester.getRect(find.byKey(secondKey));
    predictedHeroRect = pushRectTween.lerp(curve.transform(0.5));
    expect(actualHeroRect, within<Rect>(distance: epsilon, from: predictedHeroRect));

    await tester.pump(duration * 0.25);
    actualHeroRect = tester.getRect(find.byKey(secondKey));
    predictedHeroRect = pushRectTween.lerp(curve.transform(0.75));
    expect(actualHeroRect, within<Rect>(distance: epsilon, from: predictedHeroRect));

    await tester.pumpAndSettle();
    expect(tester.getCenter(find.byKey(secondKey)), const Offset(400.0 + leftPadding / 2, 300.0));

    // Verify that the rect of the firstKey Hero transforms as the
    // pushRectTween rect for the pop /two flight.

    await tester.tap(find.text('pop'));
    await tester.pump(); // begin navigation

    final RectTween popRectTween = RectTween(
Dan Field's avatar
Dan Field committed
1405 1406
      begin: const Rect.fromLTWH(350.0 + leftPadding / 2, 200.0, 100.0, 200.0),
      end: const Rect.fromLTWH(leftPadding, 0.0, 100.0, 100.0),
1407 1408 1409 1410 1411 1412
    );
    await tester.pump();
    expect(tester.getCenter(find.byKey(firstKey)), const Offset(400.0 + leftPadding / 2, 300.0));

    await tester.pump(duration * 0.25);
    actualHeroRect = tester.getRect(find.byKey(firstKey));
1413
    predictedHeroRect = popRectTween.lerp(curve.transform(0.25));
1414 1415 1416 1417
    expect(actualHeroRect, within<Rect>(distance: epsilon, from: predictedHeroRect));

    await tester.pump(duration * 0.25);
    actualHeroRect = tester.getRect(find.byKey(firstKey));
1418
    predictedHeroRect = popRectTween.lerp(curve.transform(0.5));
1419 1420 1421 1422
    expect(actualHeroRect, within<Rect>(distance: epsilon, from: predictedHeroRect));

    await tester.pump(duration * 0.25);
    actualHeroRect = tester.getRect(find.byKey(firstKey));
1423
    predictedHeroRect = popRectTween.lerp(curve.transform(0.75));
1424 1425 1426 1427 1428 1429 1430
    expect(actualHeroRect, within<Rect>(distance: epsilon, from: predictedHeroRect));

    await tester.pumpAndSettle();
    expect(tester.getCenter(find.byKey(firstKey)), const Offset(50.0 + leftPadding, 50.0));
  });


1431
  testWidgets('Pop interrupts push, reverses flight', (WidgetTester tester) async {
1432
    await tester.pumpWidget(MaterialApp(routes: routes));
1433 1434 1435
    await tester.tap(find.text('twoInset'));
    await tester.pump(); // begin navigation from / to /twoInset.

1436
    const double epsilon = 0.001;
1437
    const Duration duration = Duration(milliseconds: 300);
1438 1439 1440 1441 1442 1443 1444 1445 1446

    await tester.pump();
    final double x0 = tester.getTopLeft(find.byKey(secondKey)).dx;

    // Flight begins with the secondKey Hero widget lined up with the firstKey widget.
    expect(x0, 4.0);

    await tester.pump(duration * 0.1);
    final double x1 = tester.getTopLeft(find.byKey(secondKey)).dx;
1447

1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522
    await tester.pump(duration * 0.1);
    final double x2 = tester.getTopLeft(find.byKey(secondKey)).dx;

    await tester.pump(duration * 0.1);
    final double x3 = tester.getTopLeft(find.byKey(secondKey)).dx;

    await tester.pump(duration * 0.1);
    final double x4 = tester.getTopLeft(find.byKey(secondKey)).dx;

    // Pop route /twoInset before the push transition from / to /twoInset has finished.
    await tester.tap(find.text('pop'));


    // We expect the hero to take the same path as it did flying from /
    // to /twoInset as it does now, flying from '/twoInset' back to /. The most
    // important checks below are the first (x4) and last (x0): the hero should
    // not jump from where it was when the push transition was interrupted by a
    // pop, and it should end up where the push started.

    await tester.pump();
    expect(tester.getTopLeft(find.byKey(secondKey)).dx, closeTo(x4, epsilon));

    await tester.pump(duration * 0.1);
    expect(tester.getTopLeft(find.byKey(secondKey)).dx, closeTo(x3, epsilon));

    await tester.pump(duration * 0.1);
    expect(tester.getTopLeft(find.byKey(secondKey)).dx, closeTo(x2, epsilon));

    await tester.pump(duration * 0.1);
    expect(tester.getTopLeft(find.byKey(secondKey)).dx, closeTo(x1, epsilon));

    await tester.pump(duration * 0.1);
    expect(tester.getTopLeft(find.byKey(secondKey)).dx, closeTo(x0, epsilon));

    // Below: show that a different pop Hero path is in fact taken after
    // a completed push transition.

    // Complete the pop transition and we're back to showing /.
    await tester.pumpAndSettle();
    expect(tester.getTopLeft(find.byKey(firstKey)).dx, 4.0); // Card contents are inset by 4.0.

    // Push /twoInset and wait for the transition to finish.
    await tester.tap(find.text('twoInset'));
    await tester.pumpAndSettle();
    expect(tester.getTopLeft(find.byKey(secondKey)).dx, 54.0);

    // Start the pop transition from /twoInset to /.
    await tester.tap(find.text('pop'));
    await tester.pump();

    // Now the firstKey widget is the flying hero widget and it starts
    // out lined up with the secondKey widget.
    await tester.pump();
    expect(tester.getTopLeft(find.byKey(firstKey)).dx, 54.0);

    // x0-x4 are the top left x coordinates for the beginning 40% of
    // the incoming flight. Advance the outgoing flight to the same
    // place.
    await tester.pump(duration * 0.6);

    await tester.pump(duration * 0.1);
    expect(tester.getTopLeft(find.byKey(firstKey)).dx, isNot(closeTo(x4, epsilon)));

    await tester.pump(duration * 0.1);
    expect(tester.getTopLeft(find.byKey(firstKey)).dx, isNot(closeTo(x3, epsilon)));

    // At this point the flight path arcs do start to get pretty close so
    // there's no point in comparing them.
    await tester.pump(duration * 0.1);

    // After the remaining 40% of the incoming flight is complete, we
    // expect to end up where the outgoing flight started.
    await tester.pump(duration * 0.1);
    expect(tester.getTopLeft(find.byKey(firstKey)).dx, x0);
  });
1523 1524

  testWidgets('Can override flight shuttle', (WidgetTester tester) async {
1525 1526 1527
    await tester.pumpWidget(MaterialApp(
      home: Material(
        child: ListView(
1528 1529
          children: <Widget>[
            const Hero(tag: 'a', child: Text('foo')),
1530 1531
            Builder(builder: (BuildContext context) {
              return FlatButton(
1532
                child: const Text('two'),
1533
                onPressed: () => Navigator.push<void>(context, MaterialPageRoute<void>(
1534
                  builder: (BuildContext context) {
1535 1536
                    return Material(
                      child: Hero(
1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568
                        tag: 'a',
                        child: const Text('bar'),
                        flightShuttleBuilder: (
                          BuildContext flightContext,
                          Animation<double> animation,
                          HeroFlightDirection flightDirection,
                          BuildContext fromHeroContext,
                          BuildContext toHeroContext,
                        ) {
                          return const Text('baz');
                        },
                      ),
                    );
                  },
                )),
              );
            }),
          ],
        ),
      ),
    ));

    await tester.tap(find.text('two'));
    await tester.pump();
    await tester.pump(const Duration(milliseconds: 10));

    expect(find.text('foo'), findsNothing);
    expect(find.text('bar'), findsNothing);
    expect(find.text('baz'), findsOneWidget);
  });

  testWidgets('Can override flight launch pads', (WidgetTester tester) async {
1569 1570 1571
    await tester.pumpWidget(MaterialApp(
      home: Material(
        child: ListView(
1572
          children: <Widget>[
1573
            Hero(
1574 1575
              tag: 'a',
              child: const Text('Batman'),
1576
              placeholderBuilder: (BuildContext context, Size heroSize, Widget child) {
1577 1578 1579
                return const Text('Venom');
              },
            ),
1580 1581
            Builder(builder: (BuildContext context) {
              return FlatButton(
1582
                child: const Text('two'),
1583
                onPressed: () => Navigator.push<void>(context, MaterialPageRoute<void>(
1584
                  builder: (BuildContext context) {
1585 1586
                    return Material(
                      child: Hero(
1587 1588
                        tag: 'a',
                        child: const Text('Wolverine'),
1589
                        placeholderBuilder: (BuildContext context, Size size, Widget child) {
1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613
                          return const Text('Joker');
                        },
                      ),
                    );
                  },
                )),
              );
            }),
          ],
        ),
      ),
    ));

    await tester.tap(find.text('two'));
    await tester.pump();
    await tester.pump(const Duration(milliseconds: 10));

    expect(find.text('Batman'), findsNothing);
    // This shows up once but in the Hero because by default, the destination
    // Hero child is the widget in flight.
    expect(find.text('Wolverine'), findsOneWidget);
    expect(find.text('Venom'), findsOneWidget);
    expect(find.text('Joker'), findsOneWidget);
  });
xster's avatar
xster committed
1614 1615 1616

  testWidgets('Heroes do not transition on back gestures by default', (WidgetTester tester) async {
    await tester.pumpWidget(MaterialApp(
Dan Field's avatar
Dan Field committed
1617
     routes: routes,
xster's avatar
xster committed
1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631
    ));

    expect(find.byKey(firstKey), isOnstage);
    expect(find.byKey(firstKey), isInCard);
    expect(find.byKey(secondKey), findsNothing);

    await tester.tap(find.text('two'));
    await tester.pump();
    await tester.pump(const Duration(milliseconds: 500));

    expect(find.byKey(firstKey), findsNothing);
    expect(find.byKey(secondKey), isOnstage);
    expect(find.byKey(secondKey), isInCard);

1632 1633 1634 1635 1636
    final TestGesture  gesture = await tester.startGesture(const Offset(5.0, 200.0));
    await gesture.moveBy(const Offset(20.0, 0.0));
    await gesture.moveBy(const Offset(180.0, 0.0));
    await gesture.up();
    await tester.pump();
xster's avatar
xster committed
1637 1638 1639

    await tester.pump();

1640
    // Both Heroes exist and are seated in their normal parents.
xster's avatar
xster committed
1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651
    expect(find.byKey(firstKey), isOnstage);
    expect(find.byKey(firstKey), isInCard);
    expect(find.byKey(secondKey), isOnstage);
    expect(find.byKey(secondKey), isInCard);

    // To make sure the hero had all chances of starting.
    await tester.pump(const Duration(milliseconds: 100));
    expect(find.byKey(firstKey), isOnstage);
    expect(find.byKey(firstKey), isInCard);
    expect(find.byKey(secondKey), isOnstage);
    expect(find.byKey(secondKey), isInCard);
Dan Field's avatar
Dan Field committed
1652
  }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS,  TargetPlatform.macOS }));
xster's avatar
xster committed
1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694

  testWidgets('Heroes can transition on gesture in one frame', (WidgetTester tester) async {
    transitionFromUserGestures = true;
    await tester.pumpWidget(MaterialApp(
      routes: routes,
    ));

    await tester.tap(find.text('two'));
    await tester.pump();
    await tester.pump(const Duration(milliseconds: 500));

    expect(find.byKey(firstKey), findsNothing);
    expect(find.byKey(secondKey), isOnstage);
    expect(find.byKey(secondKey), isInCard);

    final TestGesture gesture = await tester.startGesture(const Offset(5.0, 200.0));
    await gesture.moveBy(const Offset(200.0, 0.0));
    await tester.pump();

    // We're going to page 1 so page 1's Hero is lifted into flight.
    expect(find.byKey(firstKey), isOnstage);
    expect(find.byKey(firstKey), isNotInCard);
    expect(find.byKey(secondKey), findsNothing);

    // Move further along.
    await gesture.moveBy(const Offset(500.0, 0.0));
    await tester.pump();

    // Same results.
    expect(find.byKey(firstKey), isOnstage);
    expect(find.byKey(firstKey), isNotInCard);
    expect(find.byKey(secondKey), findsNothing);

    await gesture.up();
    // Finish transition.
    await tester.pump();
    await tester.pump(const Duration(milliseconds: 500));

    // Hero A is back in the card.
    expect(find.byKey(firstKey), isOnstage);
    expect(find.byKey(firstKey), isInCard);
    expect(find.byKey(secondKey), findsNothing);
Dan Field's avatar
Dan Field committed
1695
  }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS,  TargetPlatform.macOS }));
1696

1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730
  testWidgets('Heroes animate should hide destination hero and display original hero in case of dismissed', (WidgetTester tester) async {
    transitionFromUserGestures = true;
    await tester.pumpWidget(MaterialApp(
      routes: routes,
    ));

    await tester.tap(find.text('two'));
    await tester.pumpAndSettle();

    expect(find.byKey(firstKey), findsNothing);
    expect(find.byKey(secondKey), isOnstage);
    expect(find.byKey(secondKey), isInCard);

    final TestGesture gesture = await tester.startGesture(const Offset(5.0, 200.0));
    await gesture.moveBy(const Offset(50.0, 0.0));
    await tester.pump();
    // It will only register the drag if we move a second time.
    await gesture.moveBy(const Offset(50.0, 0.0));
    await tester.pump();

    // We're going to page 1 so page 1's Hero is lifted into flight.
    expect(find.byKey(firstKey), isOnstage);
    expect(find.byKey(firstKey), isNotInCard);
    expect(find.byKey(secondKey), findsNothing);

    // Dismisses hero transition.
    await gesture.up();
    await tester.pump();
    await tester.pumpAndSettle();

    // We goes back to second page.
    expect(find.byKey(firstKey), findsNothing);
    expect(find.byKey(secondKey), isOnstage);
    expect(find.byKey(secondKey), isInCard);
Dan Field's avatar
Dan Field committed
1731
  }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS,  TargetPlatform.macOS }));
1732

1733 1734 1735 1736 1737
  testWidgets('Handles transitions when a non-default initial route is set', (WidgetTester tester) async {
    await tester.pumpWidget(MaterialApp(
      routes: routes,
      initialRoute: '/two',
    ));
1738 1739 1740
    expect(tester.takeException(), isNull);
    expect(find.text('two'), findsNothing);
    expect(find.text('three'), findsOneWidget);
1741
  });
1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769

  testWidgets('Can push/pop on outer Navigator if nested Navigator contains Heroes', (WidgetTester tester) async {
    // Regression test for https://github.com/flutter/flutter/issues/28042.

    const String heroTag = 'You are my hero!';
    final GlobalKey<NavigatorState> rootNavigator = GlobalKey();
    final GlobalKey<NavigatorState> nestedNavigator = GlobalKey();
    final Key nestedRouteHeroBottom = UniqueKey();
    final Key nestedRouteHeroTop = UniqueKey();

    await tester.pumpWidget(
      MaterialApp(
        navigatorKey: rootNavigator,
        home: Navigator(
          key: nestedNavigator,
          onGenerateRoute: (RouteSettings settings) {
            return MaterialPageRoute<void>(
              builder: (BuildContext context) {
                return Hero(
                  tag: heroTag,
                  child: Placeholder(
                    key: nestedRouteHeroBottom,
                  ),
                );
              }
            );
          },
        ),
1770
      ),
1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901
    );

    nestedNavigator.currentState.push(MaterialPageRoute<void>(
      builder: (BuildContext context) {
        return Hero(
          tag: heroTag,
          child: Placeholder(
            key: nestedRouteHeroTop,
          ),
        );
      },
    ));
    await tester.pumpAndSettle();

    // Both heroes are in the tree, one is offstage
    expect(find.byKey(nestedRouteHeroTop), findsOneWidget);
    expect(find.byKey(nestedRouteHeroBottom), findsNothing);
    expect(find.byKey(nestedRouteHeroBottom, skipOffstage: false), findsOneWidget);

    rootNavigator.currentState.push(MaterialPageRoute<void>(
      builder: (BuildContext context) {
        return const Text('Foo');
      },
    ));
    await tester.pumpAndSettle();

    expect(find.text('Foo'), findsOneWidget);
    // Both heroes are still in the tree, both are offstage.
    expect(find.byKey(nestedRouteHeroBottom), findsNothing);
    expect(find.byKey(nestedRouteHeroTop), findsNothing);
    expect(find.byKey(nestedRouteHeroBottom, skipOffstage: false), findsOneWidget);
    expect(find.byKey(nestedRouteHeroTop, skipOffstage: false), findsOneWidget);

    // Doesn't crash.
    expect(tester.takeException(), isNull);

    rootNavigator.currentState.pop();
    await tester.pumpAndSettle();

    expect(find.text('Foo'), findsNothing);
    // Both heroes are in the tree, one is offstage
    expect(find.byKey(nestedRouteHeroTop), findsOneWidget);
    expect(find.byKey(nestedRouteHeroBottom), findsNothing);
    expect(find.byKey(nestedRouteHeroBottom, skipOffstage: false), findsOneWidget);
  });

  testWidgets('Can hero from route in root Navigator to route in nested Navigator', (WidgetTester tester) async {
    const String heroTag = 'foo';
    final GlobalKey<NavigatorState> rootNavigator = GlobalKey();
    final Key smallContainer = UniqueKey();
    final Key largeContainer = UniqueKey();

    await tester.pumpWidget(
      MaterialApp(
        navigatorKey: rootNavigator,
        home: Center(
          child: Card(
            child: Hero(
              tag: heroTag,
              child: Container(
                key: largeContainer,
                color: Colors.red,
                height: 200.0,
                width: 200.0,
              ),
            ),
          ),
        ),
      ),
    );


    // The initial setup.
    expect(find.byKey(largeContainer), isOnstage);
    expect(find.byKey(largeContainer), isInCard);
    expect(find.byKey(smallContainer, skipOffstage: false), findsNothing);

    rootNavigator.currentState.push(
      MaterialPageRoute<void>(
        builder: (BuildContext context) {
          return Center(
            child: Card(
              child: Hero(
                tag: heroTag,
                child: Container(
                  key: smallContainer,
                  color: Colors.red,
                  height: 100.0,
                  width: 100.0,
                ),
              ),
            ),
          );
        }
      ),
    );
    await tester.pump();

    // The second route exists offstage.
    expect(find.byKey(largeContainer), isOnstage);
    expect(find.byKey(largeContainer), isInCard);
    expect(find.byKey(smallContainer, skipOffstage: false), isOffstage);
    expect(find.byKey(smallContainer, skipOffstage: false), isInCard);

    await tester.pump();

    // The hero started flying.
    expect(find.byKey(largeContainer), findsNothing);
    expect(find.byKey(smallContainer), isOnstage);
    expect(find.byKey(smallContainer), isNotInCard);

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

    // The hero is in-flight.
    expect(find.byKey(largeContainer), findsNothing);
    expect(find.byKey(smallContainer), isOnstage);
    expect(find.byKey(smallContainer), isNotInCard);
    final Size size = tester.getSize(find.byKey(smallContainer));
    expect(size.height, greaterThan(100));
    expect(size.width, greaterThan(100));
    expect(size.height, lessThan(200));
    expect(size.width, lessThan(200));

    await tester.pumpAndSettle();

    // The transition has ended.
    expect(find.byKey(largeContainer), findsNothing);
    expect(find.byKey(smallContainer), isOnstage);
    expect(find.byKey(smallContainer), isInCard);
    expect(tester.getSize(find.byKey(smallContainer)), const Size(100,100));
  });
1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940

  testWidgets('Hero within a Hero, throws', (WidgetTester tester) async {
    await tester.pumpWidget(
      const MaterialApp(
        home: Material(
          child: Hero(
            tag: 'a',
            child: Hero(
              tag: 'b',
              child: Text('Child of a Hero'),
            ),
          ),
        ),
      ),
    );

    expect(tester.takeException(), isAssertionError);
  });

  testWidgets('Hero within a Hero subtree, throws', (WidgetTester tester) async {
    await tester.pumpWidget(
      MaterialApp(
        home: Material(
          child: Container(
            child: const Hero(
              tag: 'a',
              child: Hero(
                tag: 'b',
                child: Text('Child of a Hero'),
              ),
            ),
          ),
        ),
      ),
    );

    expect(tester.takeException(), isAssertionError);
  });

1941
  testWidgets('Hero within a Hero subtree with Builder, throws', (WidgetTester tester) async {
1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962
    await tester.pumpWidget(
      MaterialApp(
        home: Material(
          child: Hero(
            tag: 'a',
            child: Builder(
              builder: (BuildContext context) {
                return const Hero(
                  tag: 'b',
                  child: Text('Child of a Hero'),
                );
              },
            ),
          ),
        ),
      ),
    );

    expect(tester.takeException(),isAssertionError);
  });

1963
  testWidgets('Hero within a Hero subtree with LayoutBuilder, throws', (WidgetTester tester) async {
1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983
    await tester.pumpWidget(
      MaterialApp(
        home: Material(
          child: Hero(
            tag: 'a',
            child: LayoutBuilder(
              builder: (BuildContext context, BoxConstraints constraints) {
                return const Hero(
                  tag: 'b',
                  child: Text('Child of a Hero'),
                );
              },
            ),
          ),
        ),
      ),
    );

    expect(tester.takeException(), isAssertionError);
  });
1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070

  testWidgets('Heroes fly on pushReplacement', (WidgetTester tester) async {
    // Regression test for https://github.com/flutter/flutter/issues/28041.

    const String heroTag = 'foo';
    final GlobalKey<NavigatorState> navigator = GlobalKey();
    final Key smallContainer = UniqueKey();
    final Key largeContainer = UniqueKey();

    await tester.pumpWidget(
      MaterialApp(
        navigatorKey: navigator,
        home: Center(
          child: Card(
            child: Hero(
              tag: heroTag,
              child: Container(
                key: largeContainer,
                color: Colors.red,
                height: 200.0,
                width: 200.0,
              ),
            ),
          ),
        ),
      ),
    );

    // The initial setup.
    expect(find.byKey(largeContainer), isOnstage);
    expect(find.byKey(largeContainer), isInCard);
    expect(find.byKey(smallContainer, skipOffstage: false), findsNothing);

    navigator.currentState.pushReplacement(
      MaterialPageRoute<void>(
          builder: (BuildContext context) {
            return Center(
              child: Card(
                child: Hero(
                  tag: heroTag,
                  child: Container(
                    key: smallContainer,
                    color: Colors.red,
                    height: 100.0,
                    width: 100.0,
                  ),
                ),
              ),
            );
          }
      ),
    );
    await tester.pump();

    // The second route exists offstage.
    expect(find.byKey(largeContainer), isOnstage);
    expect(find.byKey(largeContainer), isInCard);
    expect(find.byKey(smallContainer, skipOffstage: false), isOffstage);
    expect(find.byKey(smallContainer, skipOffstage: false), isInCard);

    await tester.pump();

    // The hero started flying.
    expect(find.byKey(largeContainer), findsNothing);
    expect(find.byKey(smallContainer), isOnstage);
    expect(find.byKey(smallContainer), isNotInCard);

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

    // The hero is in-flight.
    expect(find.byKey(largeContainer), findsNothing);
    expect(find.byKey(smallContainer), isOnstage);
    expect(find.byKey(smallContainer), isNotInCard);
    final Size size = tester.getSize(find.byKey(smallContainer));
    expect(size.height, greaterThan(100));
    expect(size.width, greaterThan(100));
    expect(size.height, lessThan(200));
    expect(size.width, lessThan(200));

    await tester.pumpAndSettle();

    // The transition has ended.
    expect(find.byKey(largeContainer), findsNothing);
    expect(find.byKey(smallContainer), isOnstage);
    expect(find.byKey(smallContainer), isInCard);
    expect(tester.getSize(find.byKey(smallContainer)), const Size(100,100));
  });
2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093

  testWidgets('On an iOS back swipe and snap, only a single flight should take place', (WidgetTester tester) async {
    int shuttlesBuilt = 0;
    final HeroFlightShuttleBuilder shuttleBuilder = (
      BuildContext flightContext,
      Animation<double> animation,
      HeroFlightDirection flightDirection,
      BuildContext fromHeroContext,
      BuildContext toHeroContext,
    ) {
      shuttlesBuilt += 1;
      return const Text("I'm flying in a jetplane");
    };

    final GlobalKey<NavigatorState> navigatorKey = GlobalKey();
    await tester.pumpWidget(
      CupertinoApp(
        navigatorKey: navigatorKey,
        home: Hero(
          tag: navigatorKey,
          // Since we're popping, only the destination route's builder is used.
          flightShuttleBuilder: shuttleBuilder,
          transitionOnUserGestures: true,
2094
          child: const Text('1'),
2095 2096 2097 2098 2099 2100 2101 2102 2103 2104
        ),
      ),
    );

    final CupertinoPageRoute<void> route2 = CupertinoPageRoute<void>(
      builder: (BuildContext context) {
        return CupertinoPageScaffold(
          child: Hero(
            tag: navigatorKey,
            transitionOnUserGestures: true,
2105
            child: const Text('2'),
2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133
          ),
        );
      }
    );

    navigatorKey.currentState.push(route2);
    await tester.pumpAndSettle();

    expect(shuttlesBuilt, 1);

    final TestGesture gesture = await tester.startGesture(const Offset(5.0, 200.0));
    await gesture.moveBy(const Offset(500.0, 0.0));
    await tester.pump();
    // Starting the back swipe creates a new hero shuttle.
    expect(shuttlesBuilt, 2);

    await gesture.up();
    await tester.pump();
    // After the lift, no additional shuttles should be created since it's the
    // same hero flight.
    expect(shuttlesBuilt, 2);

    // Did go far enough to snap out of this route.
    await tester.pump(const Duration(milliseconds: 301));
    expect(find.text('2'), findsNothing);
    // Still one shuttle.
    expect(shuttlesBuilt, 2);
  });
2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156

  testWidgets("From hero's state should be preserved, "
    'heroes work well with child widgets that has global keys',
    (WidgetTester tester) async {
      final GlobalKey<NavigatorState> navigatorKey = GlobalKey();
      final GlobalKey<_SimpleState> key1 = GlobalKey<_SimpleState>();
      final GlobalKey key2 = GlobalKey();

      await tester.pumpWidget(
        CupertinoApp(
          navigatorKey: navigatorKey,
          home: Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Hero(
                tag: 'hero',
                transitionOnUserGestures: true,
                child: _SimpleStatefulWidget(key: key1),
              ),
              const SizedBox(
                width: 10,
                height: 10,
                child: Text('1'),
2157 2158 2159
              ),
            ],
          ),
2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190
        ),
      );

      final CupertinoPageRoute<void> route2 = CupertinoPageRoute<void>(
        builder: (BuildContext context) {
          return CupertinoPageScaffold(
            child: Hero(
              tag: 'hero',
              transitionOnUserGestures: true,
              // key2 is a `GlobalKey`. The hero animation should not
              // assert by having the same global keyed widget in more
              // than one place in the tree.
              child: _SimpleStatefulWidget(key: key2),
            ),
          );
        }
      );

      final _SimpleState state1 = key1.currentState;
      state1.state = 1;

      navigatorKey.currentState.push(route2);
      await tester.pump();

      expect(state1.mounted, isTrue);

      await tester.pumpAndSettle();
      expect(state1.state, 1);
      // The element should be mounted and unique.
      expect(state1.mounted, isTrue);

2191
      navigatorKey.currentState.pop();
2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222
      await tester.pumpAndSettle();

      // State is preserved.
      expect(state1.state, 1);
      // The element should be mounted and unique.
      expect(state1.mounted, isTrue);
  });

  testWidgets("Hero works with images that don't have both width and height specified",
    // Regression test for https://github.com/flutter/flutter/issues/32356
    // and https://github.com/flutter/flutter/issues/31503
    (WidgetTester tester) async {
      final GlobalKey<NavigatorState> navigatorKey = GlobalKey();
      const Key imageKey1 = Key('image1');
      const Key imageKey2 = Key('image2');
      final TestImageProvider imageProvider = TestImageProvider(testImage);

      await tester.pumpWidget(
        CupertinoApp(
          navigatorKey: navigatorKey,
          home: Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Hero(
                tag: 'hero',
                transitionOnUserGestures: true,
                child: Container(
                  width: 100,
                  child: Image(
                    image: imageProvider,
                    key: imageKey1,
2223 2224
                  ),
                ),
2225 2226 2227 2228 2229
              ),
              const SizedBox(
                width: 10,
                height: 10,
                child: Text('1'),
2230 2231 2232
              ),
            ],
          ),
2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245
        ),
      );

      final CupertinoPageRoute<void> route2 = CupertinoPageRoute<void>(
        builder: (BuildContext context) {
          return CupertinoPageScaffold(
            child: Hero(
              tag: 'hero',
              transitionOnUserGestures: true,
              child: Container(
                child: Image(
                  image: imageProvider,
                  key: imageKey2,
2246
                ),
2247
              ),
2248 2249 2250 2251 2252
            ),
          );
        }
      );

2253 2254 2255 2256 2257 2258
      // Load image before measuring the `Rect` of the `RenderImage`.
      imageProvider.complete();
      await tester.pump();
      final RenderImage renderImage = tester.renderObject(
        find.descendant(of: find.byKey(imageKey1), matching: find.byType(RawImage))
      );
2259

2260 2261
      // Before push image1 should be laid out correctly.
      expect(renderImage.size, const Size(100, 100));
2262

2263 2264
      navigatorKey.currentState.push(route2);
      await tester.pump();
2265

2266 2267
      final TestGesture gesture = await tester.startGesture(const Offset(0.01, 300));
      await tester.pump();
2268

2269 2270 2271 2272
      // Move (almost) across the screen, to make the animation as close to finish
      // as possible.
      await gesture.moveTo(const Offset(800, 200));
      await tester.pump();
2273

2274 2275 2276 2277 2278
      // image1 should snap to the top left corner of the Row widget.
      expect(
        tester.getRect(find.byKey(imageKey1, skipOffstage: false)),
        rectMoreOrLessEquals(tester.getTopLeft(find.widgetWithText(Row, '1')) & const Size(100, 100), epsilon: 0.01),
      );
2279

2280 2281 2282 2283 2284 2285 2286
      // Text should respect the correct final size of image1.
      expect(
        tester.getTopRight(find.byKey(imageKey1, skipOffstage: false)).dx,
        moreOrLessEquals(tester.getTopLeft(find.text('1')).dx, epsilon: 0.01),
      );
    },
  );
2287

2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314
  // Regression test for https://github.com/flutter/flutter/issues/38183.
  testWidgets('Remove user gesture driven flights when the gesture is invalid', (WidgetTester tester) async {
    transitionFromUserGestures = true;
    await tester.pumpWidget(MaterialApp(
      routes: routes,
    ));

    await tester.tap(find.text('simple'));
    await tester.pump();
    await tester.pumpAndSettle();

    expect(find.byKey(simpleKey), findsOneWidget);

    // Tap once to trigger a flight.
    await tester.tapAt(const Offset(10, 200));
    await tester.pumpAndSettle();

    // Wait till the previous gesture is accepted.
    await tester.pump(const Duration(milliseconds: 500));

    // Tap again to trigger another flight, see if it throws.
    await tester.tapAt(const Offset(10, 200));
    await tester.pumpAndSettle();

    // The simple route should still be on top.
    expect(find.byKey(simpleKey), findsOneWidget);
    expect(tester.takeException(), isNull);
Dan Field's avatar
Dan Field committed
2315
  }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS,  TargetPlatform.macOS }));
2316

2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366
  // Regression test for https://github.com/flutter/flutter/issues/40239.
  testWidgets(
    'In a pop transition, when fromHero is null, the to hero should eventually become visible',
    (WidgetTester tester) async {
      final GlobalKey<NavigatorState> navigatorKey = GlobalKey();
      StateSetter setState;
      bool shouldDisplayHero = true;
      await tester.pumpWidget(
        CupertinoApp(
          navigatorKey: navigatorKey,
          home: Hero(
            tag: navigatorKey,
            child: const Placeholder(),
          ),
        ),
      );

      final CupertinoPageRoute<void> route2 = CupertinoPageRoute<void>(
        builder: (BuildContext context) {
          return CupertinoPageScaffold(
            child: StatefulBuilder(
              builder: (BuildContext context, StateSetter setter) {
                setState = setter;
                return shouldDisplayHero
                  ? Hero(tag: navigatorKey, child: const Text('text'))
                  : const SizedBox();
              },
            ),
          );
        },
      );

      navigatorKey.currentState.push(route2);
      await tester.pumpAndSettle();

      expect(find.text('text'), findsOneWidget);
      expect(find.byType(Placeholder), findsNothing);

      setState(() { shouldDisplayHero = false; });
      await tester.pumpAndSettle();

      expect(find.text('text'), findsNothing);

      navigatorKey.currentState.pop();
      await tester.pumpAndSettle();

      expect(find.byType(Placeholder), findsOneWidget);
    },
  );

2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444
  testWidgets('popped hero uses fastOutSlowIn curve', (WidgetTester tester) async {
    final Key container1 = UniqueKey();
    final Key container2 = UniqueKey();
    final GlobalKey<NavigatorState> navigator = GlobalKey<NavigatorState>();

    final Animatable<Size> tween = SizeTween(
      begin: const Size(200, 200),
      end: const Size(100, 100),
    ).chain(CurveTween(curve: Curves.fastOutSlowIn));


    await tester.pumpWidget(
      MaterialApp(
        navigatorKey: navigator,
        home: Scaffold(
          body: Center(
            child: Hero(
              tag: 'test',
              createRectTween: (Rect begin, Rect end) {
                return RectTween(begin: begin, end: end);
              },
              child: Container(
                key: container1,
                height: 100,
                width: 100,
              ),
            ),
          ),
        ),
      ),
    );
    final Size originalSize = tester.getSize(find.byKey(container1));
    expect(originalSize, const Size(100, 100));

    navigator.currentState.push(MaterialPageRoute<void>(builder: (BuildContext context) {
      return Scaffold(
        body: Center(
          child: Hero(
            tag: 'test',
            createRectTween: (Rect begin, Rect end) {
              return RectTween(begin: begin, end: end);
            },
            child: Container(
              key: container2,
              height: 200,
              width: 200,
            ),
          ),
        ),
      );
    }));
    await tester.pumpAndSettle();
    final Size newSize = tester.getSize(find.byKey(container2));
    expect(newSize, const Size(200, 200));

    navigator.currentState.pop();
    await tester.pump();

    // Jump 25% into the transition (total length = 300ms)
    await tester.pump(const Duration(milliseconds: 75)); // 25% of 300ms
    Size heroSize = tester.getSize(find.byKey(container1));
    expect(heroSize, tween.transform(0.25));

    // Jump to 50% into the transition.
    await tester.pump(const Duration(milliseconds: 75)); // 25% of 300ms
    heroSize = tester.getSize(find.byKey(container1));
    expect(heroSize, tween.transform(0.50));

    // Jump to 75% into the transition.
    await tester.pump(const Duration(milliseconds: 75)); // 25% of 300ms
    heroSize = tester.getSize(find.byKey(container1));
    expect(heroSize, tween.transform(0.75));

    // Jump to 100% into the transition.
    await tester.pump(const Duration(milliseconds: 75)); // 25% of 300ms
    heroSize = tester.getSize(find.byKey(container1));
    expect(heroSize, tween.transform(1.0));
  });
2445
}