page.dart 21.3 KB
Newer Older
1 2 3 4 5
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'package:flutter/foundation.dart';
6 7
import 'package:flutter/gestures.dart';
import 'package:flutter/rendering.dart';
8 9
import 'package:flutter/widgets.dart';

10 11
const double _kBackGestureWidth = 20.0;
const double _kMinFlingVelocity = 1.0; // Screen widths per second.
12

13 14 15 16 17 18 19 20 21 22 23 24
// Fractional offset from offscreen to the right to fully on screen.
final FractionalOffsetTween _kRightMiddleTween = new FractionalOffsetTween(
  begin: FractionalOffset.topRight,
  end: FractionalOffset.topLeft,
);

// Fractional offset from fully on screen to 1/3 offscreen to the left.
final FractionalOffsetTween _kMiddleLeftTween = new FractionalOffsetTween(
  begin: FractionalOffset.topLeft,
  end: const FractionalOffset(-1.0/3.0, 0.0),
);

25 26 27 28 29 30
// Fractional offset from offscreen below to fully on screen.
final FractionalOffsetTween _kBottomUpTween = new FractionalOffsetTween(
  begin: FractionalOffset.bottomLeft,
  end: FractionalOffset.topLeft,
);

31
// Custom decoration from no shadow to page shadow mimicking iOS page
32 33 34 35 36 37 38 39 40 41
// transitions using gradients.
final DecorationTween _kGradientShadowTween = new DecorationTween(
  begin: _CupertinoEdgeShadowDecoration.none, // No decoration initially.
  end: const _CupertinoEdgeShadowDecoration(
    edgeGradient: const LinearGradient(
      // Spans 5% of the page.
      begin: const FractionalOffset(0.95, 0.0),
      end: FractionalOffset.topRight,
      // Eyeballed gradient used to mimic a drop shadow on the left side only.
      colors: const <Color>[
42
        const Color(0x00000000),
43 44 45 46 47
        const Color(0x04000000),
        const Color(0x12000000),
        const Color(0x38000000)
      ],
      stops: const <double>[0.0, 0.3, 0.6, 1.0],
48
    ),
49 50 51
  ),
);

52 53
/// A modal route that replaces the entire screen with an iOS transition.
///
54 55
/// The page slides in from the right and exits in reverse. The page also shifts
/// to the left in parallax when another page enters to cover it.
56
///
57 58
/// The page slides in from the bottom and exits in reverse with no parallax
/// effect for fullscreen dialogs.
59 60 61 62 63
///
/// By default, when a modal route is replaced by another, the previous route
/// remains in memory. To free all the resources when this is not necessary, set
/// [maintainState] to false.
///
64 65 66 67
/// The type `T` specifies the return type of the route which can be supplied as
/// the route is popped from the stack via [Navigator.pop] when an optional
/// `result` can be provided.
///
68 69
/// See also:
///
70 71
///  * [MaterialPageRoute] for an adaptive [PageRoute] that uses a platform
///    appropriate transition.
72 73
class CupertinoPageRoute<T> extends PageRoute<T> {
  /// Creates a page route for use in an iOS designed app.
74 75 76
  ///
  /// The [builder], [settings], [maintainState], and [fullscreenDialog]
  /// arguments must not be null.
77 78 79 80 81
  CupertinoPageRoute({
    @required this.builder,
    RouteSettings settings: const RouteSettings(),
    this.maintainState: true,
    bool fullscreenDialog: false,
82
    this.hostRoute,
83
  }) : assert(builder != null),
84 85 86 87
       assert(settings != null),
       assert(maintainState != null),
       assert(fullscreenDialog != null),
       assert(opaque), // PageRoute makes it return true.
88 89 90 91
       super(settings: settings, fullscreenDialog: fullscreenDialog);

  /// Builds the primary contents of the route.
  final WidgetBuilder builder;
92

93 94
  @override
  final bool maintainState;
95

96 97 98 99 100 101 102 103 104 105
  /// The route that owns this one.
  ///
  /// The [MaterialPageRoute] creates a [CupertinoPageRoute] to handle iOS-style
  /// navigation. When this happens, the [MaterialPageRoute] is the [hostRoute]
  /// of this [CupertinoPageRoute].
  ///
  /// The [hostRoute] is responsible for calling [dispose] on the route. When
  /// there is a [hostRoute], the [CupertinoPageRoute] must not be [install]ed.
  final PageRoute<T> hostRoute;

106 107
  @override
  Duration get transitionDuration => const Duration(milliseconds: 350);
108 109

  @override
110
  Color get barrierColor => null;
111 112

  @override
113 114
  bool canTransitionFrom(TransitionRoute<dynamic> previousRoute) {
    return previousRoute is CupertinoPageRoute;
115
  }
116

117
  @override
118 119 120
  bool canTransitionTo(TransitionRoute<dynamic> nextRoute) {
    // Don't perform outgoing animation if the next route is a fullscreen dialog.
    return nextRoute is CupertinoPageRoute && !nextRoute.fullscreenDialog;
121 122
  }

123 124 125 126 127 128 129 130 131 132 133 134 135
  @override
  void install(OverlayEntry insertionPoint) {
    assert(() {
      if (hostRoute == null)
        return true;
      throw new FlutterError(
        'Cannot install a subsidiary route (one with a hostRoute).\n'
        'This route ($this) cannot be installed, because it has a host route ($hostRoute).'
      );
    });
    super.install(insertionPoint);
  }

136
  @override
137 138
  void dispose() {
    _backGestureController?.dispose();
139 140
    _backGestureController = null;
    super.dispose();
141 142
  }

143
  _CupertinoBackGestureController _backGestureController;
144

145
  /// Whether a pop gesture is currently underway.
146
  ///
147 148 149
  /// This starts returning true when the [startPopGesture] method returns a new
  /// [NavigationGestureController]. It returns false if that has not yet
  /// occurred or if the most recent such gesture has completed.
150 151 152
  ///
  /// See also:
  ///
153 154 155
  ///  * [popGestureEnabled], which returns whether a pop gesture is appropriate
  ///    in the first place.
  bool get popGestureInProgress => _backGestureController != null;
156

157 158 159 160 161 162
  /// Whether a pop gesture will be considered acceptable by [startPopGesture].
  ///
  /// This returns true if the user can edge-swipe to a previous route,
  /// otherwise false.
  ///
  /// This will return false if [popGestureInProgress] is true.
163
  ///
164 165 166 167 168 169 170 171 172 173 174
  /// This should only be used between frames, not during build.
  bool get popGestureEnabled {
    final PageRoute<T> route = hostRoute ?? this;
    // If there's nothing to go back to, then obviously we don't support
    // the back gesture.
    if (route.isFirst)
      return false;
    // If the route wouldn't actually pop if we popped it, then the gesture
    // would be really confusing (or would skip internal routes), so disallow it.
    if (route.willHandlePopInternally)
      return false;
175 176
    // If attempts to dismiss this route might be vetoed such as in a page
    // with forms, then do not allow the user to dismiss the route with a swipe.
177 178
    if (route.hasScopedWillPopCallback)
      return false;
179 180
    // Fullscreen dialogs aren't dismissable by back swipe.
    if (fullscreenDialog)
181 182 183 184 185 186 187 188 189 190
      return false;
    // If we're in an animation already, we cannot be manually swiped.
    if (route.controller.status != AnimationStatus.completed)
      return false;
    // If we're in a gesture already, we cannot start another.
    if (popGestureInProgress)
      return false;
    // Looks like a back gesture would be welcome!
    return true;
  }
191

192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
  /// Begin dismissing this route from a horizontal swipe, if appropriate.
  ///
  /// Swiping will be disabled if the page is a fullscreen dialog or if
  /// dismissals can be overriden because a [WillPopCallback] was
  /// defined for the route.
  ///
  /// When this method decides a pop gesture is appropriate, it returns a
  /// [CupertinoBackGestureController].
  ///
  /// See also:
  ///
  ///  * [hasScopedWillPopCallback], which is true if a `willPop` callback
  ///    is defined for this route.
  ///  * [popGestureEnabled], which returns whether a pop gesture is
  ///    appropriate.
  ///  * [Route.startPopGesture], which describes the contract that this method
  ///    must implement.
  _CupertinoBackGestureController _startPopGesture() {
    assert(!popGestureInProgress);
    assert(popGestureEnabled);
    final PageRoute<T> route = hostRoute ?? this;
    _backGestureController = new _CupertinoBackGestureController(
      navigator: route.navigator,
      controller: route.controller,
      onEnded: _endPopGesture,
    );
218 219
    return _backGestureController;
  }
220

221 222 223 224 225 226 227
  void _endPopGesture() {
    // In practice this only gets called if for some reason popping the route
    // did not cause this route to get disposed.
    _backGestureController?.dispose();
    _backGestureController = null;
  }

228
  @override
229 230 231 232 233 234 235 236 237 238 239 240 241
  Widget buildPage(BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation) {
    final Widget result = builder(context);
    assert(() {
      if (result == null) {
        throw new FlutterError(
          'The builder for route "${settings.name}" returned null.\n'
          'Route builders must never return null.'
        );
      }
      return true;
    });
    return result;
  }
242

243 244
  @override
  Widget buildTransitions(BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child) {
245
    if (fullscreenDialog) {
246 247 248 249
      return new CupertinoFullscreenDialogTransition(
        animation: animation,
        child: child,
      );
250
    } else {
251 252 253
      return new CupertinoPageTransition(
        primaryRouteAnimation: animation,
        secondaryRouteAnimation: secondaryAnimation,
254 255 256 257 258 259 260 261
        // In the middle of a back gesture drag, let the transition be linear to
        // match finger motions.
        linearTransition: popGestureInProgress,
        child: new _CupertinoBackGestureDetector(
          enabledCallback: () => popGestureEnabled,
          onStartPopGesture: _startPopGesture,
          child: child,
        ),
262
      );
263
    }
264
  }
265 266 267

  @override
  String get debugLabel => '${super.debugLabel}(${settings.name})';
268 269
}

270
/// Provides an iOS-style page transition animation.
271 272 273
///
/// The page slides in from the right and exits in reverse. It also shifts to the left in
/// a parallax motion when another page enters to cover it.
274
class CupertinoPageTransition extends StatelessWidget {
275 276 277 278 279 280 281 282
  /// Creates an iOS-style page transition.
  ///
  ///  * `primaryRouteAnimation` is a linear route animation from 0.0 to 1.0
  ///    when this screen is being pushed.
  ///  * `secondaryRouteAnimation` is a linear route animation from 0.0 to 1.0
  ///    when another screen is being pushed on top of this one.
  ///  * `linearTransition` is whether to perform primary transition linearly.
  ///    Used to precisely track back gesture drags.
283 284
  CupertinoPageTransition({
    Key key,
285 286
    @required Animation<double> primaryRouteAnimation,
    @required Animation<double> secondaryRouteAnimation,
287
    @required this.child,
288
    bool linearTransition,
289
  }) :
290 291
      _primaryPositionAnimation = linearTransition
        ? _kRightMiddleTween.animate(primaryRouteAnimation)
292 293
        : _kRightMiddleTween.animate(
            new CurvedAnimation(
294
              parent: primaryRouteAnimation,
295 296 297 298
              curve: Curves.easeOut,
              reverseCurve: Curves.easeIn,
            )
          ),
299
      _secondaryPositionAnimation = _kMiddleLeftTween.animate(
300
        new CurvedAnimation(
301
          parent: secondaryRouteAnimation,
302 303 304 305
          curve: Curves.easeOut,
          reverseCurve: Curves.easeIn,
        )
      ),
306 307 308 309 310 311
      _primaryShadowAnimation = _kGradientShadowTween.animate(
        new CurvedAnimation(
          parent: primaryRouteAnimation,
          curve: Curves.easeOut,
        )
      ),
312
      super(key: key);
313 314

  // When this page is coming in to cover another page.
315
  final Animation<FractionalOffset> _primaryPositionAnimation;
316
  // When this page is becoming covered by another page.
317 318
  final Animation<FractionalOffset> _secondaryPositionAnimation;
  final Animation<Decoration> _primaryShadowAnimation;
319 320

  /// The widget below this widget in the tree.
321 322 323 324 325 326 327
  final Widget child;

  @override
  Widget build(BuildContext context) {
    // TODO(ianh): tell the transform to be un-transformed for hit testing
    // but not while being controlled by a gesture.
    return new SlideTransition(
328
      position: _secondaryPositionAnimation,
329
      child: new SlideTransition(
330 331 332
        position: _primaryPositionAnimation,
        child: new DecoratedBoxTransition(
          decoration: _primaryShadowAnimation,
333 334 335
          child: child,
        ),
      ),
336 337 338 339
    );
  }
}

340 341 342 343
/// An iOS-style transition used for summoning fullscreen dialogs.
///
/// For example, used when creating a new calendar event by bringing in the next
/// screen from the bottom.
344
class CupertinoFullscreenDialogTransition extends StatelessWidget {
345
  /// Creates an iOS-style transition used for summoning fullscreen dialogs.
346 347 348 349
  CupertinoFullscreenDialogTransition({
    Key key,
    @required Animation<double> animation,
    @required this.child,
350 351 352 353 354 355 356
  }) : _positionAnimation = _kBottomUpTween.animate(
         new CurvedAnimation(
           parent: animation,
           curve: Curves.easeInOut,
         )
       ),
       super(key: key);
357

358
  final Animation<FractionalOffset> _positionAnimation;
359 360

  /// The widget below this widget in the tree.
361
  final Widget child;
362 363

  @override
364 365
  Widget build(BuildContext context) {
    return new SlideTransition(
366
      position: _positionAnimation,
367 368
      child: child,
    );
369 370 371
  }
}

372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456
/// This is the widget side of [_CupertinoBackGestureController].
///
/// This widget provides a gesture recognizer which, when it determines the
/// route can be closed with a back gesture, creates the controller and
/// feeds it the input from the gesture recognizer.
class _CupertinoBackGestureDetector extends StatefulWidget {
  const _CupertinoBackGestureDetector({
    Key key,
    @required this.enabledCallback,
    @required this.onStartPopGesture,
    @required this.child,
  }) : assert(enabledCallback != null),
       assert(onStartPopGesture != null),
       assert(child != null),
       super(key: key);

  final Widget child;

  final ValueGetter<bool> enabledCallback;

  final ValueGetter<_CupertinoBackGestureController> onStartPopGesture;

  @override
  _CupertinoBackGestureDetectorState createState() => new _CupertinoBackGestureDetectorState();
}

class _CupertinoBackGestureDetectorState extends State<_CupertinoBackGestureDetector> {
  _CupertinoBackGestureController _backGestureController;

  HorizontalDragGestureRecognizer _recognizer;

  @override
  void initState() {
    super.initState();
    _recognizer = new HorizontalDragGestureRecognizer(debugOwner: this)
      ..onStart = _handleDragStart
      ..onUpdate = _handleDragUpdate
      ..onEnd = _handleDragEnd
      ..onCancel = _handleDragCancel;
  }

  @override
  void dispose() {
    _recognizer.dispose();
    super.dispose();
  }

  void _handleDragStart(DragStartDetails details) {
    assert(mounted);
    assert(_backGestureController == null);
    _backGestureController = widget.onStartPopGesture();
  }

  void _handleDragUpdate(DragUpdateDetails details) {
    assert(mounted);
    assert(_backGestureController != null);
    _backGestureController.dragUpdate(details.primaryDelta / context.size.width);
  }

  void _handleDragEnd(DragEndDetails details) {
    assert(mounted);
    assert(_backGestureController != null);
    _backGestureController.dragEnd(details.velocity.pixelsPerSecond.dx / context.size.width);
    _backGestureController = null;
  }

  void _handleDragCancel() {
    assert(mounted);
    // This can be called even if start is not called, paired with the "down" event
    // that we don't consider here.
    _backGestureController?.dragEnd(0.0);
    _backGestureController = null;
  }

  void _handlePointerDown(PointerDownEvent event) {
    if (widget.enabledCallback())
      _recognizer.addPointer(event);
  }

  @override
  Widget build(BuildContext context) {
    return new Stack(
      fit: StackFit.passthrough,
      children: <Widget>[
        widget.child,
457 458 459 460 461 462 463 464 465
        new Positioned(
          left: 0.0,
          width: _kBackGestureWidth,
          top: 0.0,
          bottom: 0.0,
          child: new Listener(
            onPointerDown: _handlePointerDown,
            behavior: HitTestBehavior.translucent,
          ),
466 467 468 469 470 471 472
        ),
      ],
    );
  }
}


473 474
/// A controller for an iOS-style back gesture.
///
475 476 477 478 479
/// This is created by a [CupertinoPageRoute] in response from a gesture caught
/// by a [_CupertinoBackGestureDetector] widget, which then also feeds it input
/// from the gesture. It controls the animation controller owned by the route,
/// based on the input provided by the gesture detector.
class _CupertinoBackGestureController {
480 481 482
  /// Creates a controller for an iOS-style back gesture.
  ///
  /// The [navigator] and [controller] arguments must not be null.
483 484
  _CupertinoBackGestureController({
    @required this.navigator,
485
    @required this.controller,
486 487 488 489 490 491 492 493 494
    @required this.onEnded,
  }) : assert(navigator != null),
       assert(controller != null),
       assert(onEnded != null) {
    navigator.didStartUserGesture();
  }

  /// The navigator that this object is controlling.
  final NavigatorState navigator;
495

496 497
  /// The animation controller that the route uses to drive its transition
  /// animation.
498 499
  final AnimationController controller;

500
  final VoidCallback onEnded;
501

502 503 504 505
  bool _animating = false;

  /// The drag gesture has changed by [fractionalDelta]. The total range of the
  /// drag should be 0.0 to 1.0.
506 507 508 509
  void dragUpdate(double delta) {
    controller.value -= delta;
  }

510 511 512 513 514 515
  /// The drag gesture has ended with a horizontal motion of
  /// [fractionalVelocity] as a fraction of screen width per second.
  void dragEnd(double velocity) {
    // Fling in the appropriate direction.
    // AnimationController.fling is guaranteed to
    // take at least one frame.
516 517 518 519 520 521 522
    if (velocity.abs() >= _kMinFlingVelocity) {
      controller.fling(velocity: -velocity);
    } else if (controller.value <= 0.5) {
      controller.fling(velocity: -1.0);
    } else {
      controller.fling(velocity: 1.0);
    }
523 524 525
    assert(controller.isAnimating);
    assert(controller.status != AnimationStatus.completed);
    assert(controller.status != AnimationStatus.dismissed);
526 527

    // Don't end the gesture until the transition completes.
528 529
    _animating = true;
    controller.addStatusListener(_handleStatusChanged);
530 531
  }

532
  void _handleStatusChanged(AnimationStatus status) {
533 534 535
    assert(_animating);
    controller.removeStatusListener(_handleStatusChanged);
    _animating = false;
536
    if (status == AnimationStatus.dismissed)
537 538 539 540 541 542 543 544
      navigator.pop(); // this will cause the route to get disposed, which will dispose us
    onEnded(); // this will call dispose if popping the route failed to do so
  }

  void dispose() {
    if (_animating)
      controller.removeStatusListener(_handleStatusChanged);
    navigator.didStopUserGesture();
545 546
  }
}
547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 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

/// A custom [Decoration] used to paint an extra shadow on the left edge of the
/// box it's decorating. It's like a [BoxDecoration] with only a gradient except
/// it paints to the left of the box instead of behind the box.
class _CupertinoEdgeShadowDecoration extends Decoration {
  const _CupertinoEdgeShadowDecoration({ this.edgeGradient });

  /// A Decoration with no decorating properties.
  static const _CupertinoEdgeShadowDecoration none =
      const _CupertinoEdgeShadowDecoration();

  /// A gradient to draw to the left of the box being decorated.
  /// FractionalOffsets are relative to the original box translated one box
  /// width to the left.
  final LinearGradient edgeGradient;

  /// Linearly interpolate between two edge shadow decorations decorations.
  ///
  /// See also [Decoration.lerp].
  static _CupertinoEdgeShadowDecoration lerp(
    _CupertinoEdgeShadowDecoration a,
    _CupertinoEdgeShadowDecoration b,
    double t
  ) {
    if (a == null && b == null)
      return null;
    return new _CupertinoEdgeShadowDecoration(
      edgeGradient: LinearGradient.lerp(a?.edgeGradient, b?.edgeGradient, t),
    );
  }

  @override
  _CupertinoEdgeShadowDecoration lerpFrom(Decoration a, double t) {
    if (a is! _CupertinoEdgeShadowDecoration)
      return _CupertinoEdgeShadowDecoration.lerp(null, this, t);
    return _CupertinoEdgeShadowDecoration.lerp(a, this, t);
  }

  @override
  _CupertinoEdgeShadowDecoration lerpTo(Decoration b, double t) {
    if (b is! _CupertinoEdgeShadowDecoration)
      return _CupertinoEdgeShadowDecoration.lerp(this, null, t);
    return _CupertinoEdgeShadowDecoration.lerp(this, b, t);
  }

  @override
  _CupertinoEdgeShadowPainter createBoxPainter([VoidCallback onChanged]) {
    return new _CupertinoEdgeShadowPainter(this, onChanged);
  }

  @override
  bool operator ==(dynamic other) {
    if (identical(this, other))
      return true;
    if (other.runtimeType != _CupertinoEdgeShadowDecoration)
      return false;
    final _CupertinoEdgeShadowDecoration typedOther = other;
    return edgeGradient == typedOther.edgeGradient;
  }

  @override
  int get hashCode {
    return edgeGradient.hashCode;
  }
611 612

  @override
613 614 615
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
    properties.add(new DiagnosticsProperty<LinearGradient>('edgeGradient', edgeGradient));
616
  }
617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643
}

/// A [BoxPainter] used to draw the page transition shadow using gradients.
class _CupertinoEdgeShadowPainter extends BoxPainter {
  _CupertinoEdgeShadowPainter(
    this._decoration,
    VoidCallback onChange
  ) : assert(_decoration != null),
      super(onChange);

  final _CupertinoEdgeShadowDecoration _decoration;

  @override
  void paint(Canvas canvas, Offset offset, ImageConfiguration configuration) {
    final LinearGradient gradient = _decoration.edgeGradient;
    if (gradient == null)
      return;
    // The drawable space for the gradient is a rect with the same size as
    // its parent box one box width to the left of the box.
    final Rect rect =
        (offset & configuration.size).translate(-configuration.size.width, 0.0);
    final Paint paint = new Paint()
      ..shader = gradient.createShader(rect);

    canvas.drawRect(rect, paint);
  }
}