sheet_route.dart 15 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 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 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 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 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// ignore_for_file: deprecated_member_use

import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
import 'package:sheet/route.dart';
import 'package:sheet/sheet.dart';

// TODO(jaime): Arbitrary values, keep them or make SheetRoute abstract
const double _kWillPopThreshold = 0.8;
const Duration _kSheetTransitionDuration = Duration(milliseconds: 400);
const Color _kBarrierColor = Color(0x59000000);

/// A modal route that overlays a widget over the current route and animates
/// it from the bottom
///
/// 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.
///
///
/// 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] by providing the
/// optional `result` argument.
///
/// See also:
///
///  * [SheetPage], which is a [Page] of this class.
///  * [CupertinoSheetRoute], which is has an iOS appearance
class SheetRoute<T> extends PageRoute<T> with DelegatedTransitionsRoute<T> {
  SheetRoute({
    required this.builder,
    this.initialExtent = 1,
    this.stops,
    this.draggable = true,
    this.fit = SheetFit.expand,
    this.physics,
    this.animationCurve,
    Duration? duration,
    this.sheetLabel,
    this.barrierLabel,
    this.barrierColor = _kBarrierColor,
    this.barrierDismissible = true,
    this.maintainState = true,
    this.willPopThreshold = _kWillPopThreshold,
    this.decorationBuilder,
    super.settings,
  })  : transitionDuration = duration ?? _kSheetTransitionDuration,
        super(fullscreenDialog: true);

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

  /// Relative extent up to where the sheet is animated when pushed for
  /// the first time.
  /// Values can't only be between
  ///    - 0: hidden
  ///    - 1: fully animated to the top
  /// By default it is 1
  final double initialExtent;

  /// Possible stops where the sheet can be snapped when dragged
  /// Values can only be between 0 and 1
  /// By default it is null
  final List<double>? stops;

  /// How to size the builder content in the sheet route.
  ///
  /// The constraints passed into the [Sheet] child are either
  /// loosened ([SheetFit.loose]) or tightened to their biggest size
  /// ([SheetFit.expand]).
  final SheetFit fit;

  /// {@macro flutter.widgets.sheet.physics}
  final SheetPhysics? physics;

  /// Defines if the sheet can be translated by user dragging.
  /// If false the route can still be closed by tapping the barrier if
  /// barrierDismissible is true or by [Navigator.pop]
  final bool draggable;

  /// Curve for the transition animation
  final Curve? animationCurve;

  /// Drag threshold to block any interaction if [Route.willPop] returns false
  /// See also:
  ///   * [WillPopScope], that allow to block an attempt to close a [ModalRoute]
  final double willPopThreshold;

  /// {@macro flutter.widgets.TransitionRoute.transitionDuration}
  @override
  final Duration transitionDuration;

  /// The semantic label used for a sheet modal route.
  final String? sheetLabel;

  /// Wraps the child in a custom sheet decoration appearance
  ///
  /// The default value is null.
  final SheetDecorationBuilder? decorationBuilder;

  @override
  final bool barrierDismissible;

  @override
  final Color? barrierColor;

  @override
  final String? barrierLabel;

  AnimationController? _routeAnimationController;

  late final SheetController _sheetController;
  SheetController get sheetController => _sheetController;

  @override
  void install() {
    _sheetController = createSheetController();
    super.install();
  }

  /// Called to create the sheet controller that will drive the
  /// sheet transitions
  SheetController createSheetController() {
    return SheetController();
  }

  @override
  AnimationController createAnimationController() {
    assert(_routeAnimationController == null);
    _routeAnimationController = AnimationController(
      vsync: navigator!,
      duration: transitionDuration,
    );
    return _routeAnimationController!;
  }

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

  @override
  Widget buildPage(BuildContext context, Animation<double> animation,
      Animation<double> secondaryAnimation) {
    return _SheetRouteContainer(sheetRoute: this);
  }

  @override
  bool canTransitionTo(TransitionRoute<dynamic> nextRoute) =>
      nextRoute is SheetRoute;

  @override
  bool canTransitionFrom(TransitionRoute<dynamic> previousRoute) =>
      previousRoute is PageRoute;

  /// {@macro flutter.widgets.modalRoute.maintainState}
  @override
  final bool maintainState;

  @override
  bool get opaque => false;

  @override
  bool canDriveSecondaryTransitionForPreviousRoute(
      Route<dynamic> previousRoute) {
    return true;
  }

  @override
  Widget buildSecondaryTransitionForPreviousRoute(BuildContext context,
      Animation<double> secondaryAnimation, Widget child) {
    return child;
  }

  /// Returns true if the controller should prevent popping for a given extent
  @protected
  bool shouldPreventPopForExtent(double extent) {
    return extent < willPopThreshold &&
        hasScopedWillPopCallback &&
        controller!.velocity <= 0;
  }

  Widget buildSheet(BuildContext context, Widget child) {
    SheetPhysics? effectivePhysics = SnapSheetPhysics(
      stops: stops ?? <double>[0, 1],
      parent: physics,
    );
    if (!draggable) {
      effectivePhysics = const NeverDraggableSheetPhysics();
    }
    return Sheet.raw(
      initialExtent: initialExtent,
      decorationBuilder: decorationBuilder,
      fit: fit,
      physics: effectivePhysics,
      controller: sheetController,
      child: child,
    );
  }
}

/// A page that creates a material style [SheetRoute].
///
/// 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.
///
/// The `fullscreenDialog` property specifies whether the incoming route is a
/// fullscreen modal dialog. On iOS, those routes animate from the bottom to the
/// top rather than horizontally.
///
/// 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] by providing the
/// optional `result` argument.
///
/// See also:
///
///
///  * [SheetPageRoute], which is the [PageRoute] version of this class
class SheetPage<T> extends Page<T> {
  /// Creates a material page.
  const SheetPage(
      {required this.child,
      this.maintainState = true,
      super.key,
      super.name,
      super.arguments,
      this.initialExtent = 1,
      this.stops,
      this.draggable = true,
      this.fit = SheetFit.expand,
      this.physics,
      this.animationCurve,
      Duration? duration,
      this.sheetLabel,
      this.barrierLabel,
      this.barrierColor = _kBarrierColor,
      this.barrierDismissible = true,
      this.willPopThreshold = _kWillPopThreshold,
      this.decorationBuilder})
      : transitionDuration = duration ?? _kSheetTransitionDuration;

  /// Relative extent up to where the sheet is animated when pushed for
  /// the first time.
  /// Values can't only be between
  ///    - 0: hidden
  ///    - 1: fully animated to the top
  /// By default it is 1
  final double initialExtent;

  /// Possible stops where the sheet can be snapped when dragged
  /// Values can only be between 0 and 1
  /// By default it is null
  final List<double>? stops;

  /// How to size the builder content in the sheet route.
  ///
  /// The constraints passed into the [Sheet] child are either
  /// loosened ([SheetFit.loose]) or tightened to their biggest size
  /// ([SheetFit.expand]).
  final SheetFit fit;

  /// {@macro flutter.widgets.sheet.physics}
  final SheetPhysics? physics;

  /// The content to be shown in the [Route] created by this page.
  final Widget child;

  /// {@macro flutter.widgets.modalRoute.maintainState}
  final bool maintainState;

  /// Defines if the sheet can be translated by user dragging.
  /// If false the route can still be closed by tapping the barrier if
  /// barrierDismissible is true or by [Navigator.pop]
  final bool draggable;

  /// Curve for the transition animation
  final Curve? animationCurve;

  /// Drag threshold to block any interaction if [Route.willPop] returns false
  /// See also:
  ///   * [WillPopScope], that allow to block an attempt to close a [ModalRoute]
  final double willPopThreshold;

  /// {@macro flutter.widgets.TransitionRoute.transitionDuration}
  final Duration transitionDuration;

  /// The semantic label used for a sheet modal route.
  final String? sheetLabel;

  final bool barrierDismissible;

  final Color? barrierColor;

  final String? barrierLabel;

  /// Wraps the child in a custom sheet decoration appearance
  ///
  /// The default value is null.
  final SheetDecorationBuilder? decorationBuilder;

  @override
  Route<T> createRoute(BuildContext context) {
    return _PageBasedSheetRoute<T>(
      page: this,
      physics: physics,
      fit: fit,
      stops: stops,
      initialExtent: initialExtent,
      barrierDismissible: barrierDismissible,
      barrierColor: barrierColor,
      draggable: draggable,
      animationCurve: animationCurve,
      duration: transitionDuration,
      decorationBuilder: decorationBuilder,
    );
  }
}

// A page-based version of SheetRoute.
//
// This route uses the builder from the page to build its content. This ensures
// the content is up to date after page updates.
class _PageBasedSheetRoute<T> extends SheetRoute<T> {
  _PageBasedSheetRoute({
    required SheetPage<T> page,
    super.physics,
    required super.fit,
    super.animationCurve,
    required super.barrierDismissible,
    super.barrierColor,
    required super.draggable,
    super.duration,
    super.stops,
    required super.initialExtent,
    super.decorationBuilder,
  }) : super(settings: page, builder: (BuildContext context) => page.child);

  SheetPage<T> get _page => settings as SheetPage<T>;

  @override
  WidgetBuilder get builder => (context) => _page.child;

  @override
  bool get maintainState => _page.maintainState;

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

class _SheetRouteContainer extends StatefulWidget {
  const _SheetRouteContainer({required this.sheetRoute});

  final SheetRoute<dynamic> sheetRoute;
  @override
  __SheetRouteContainerState createState() => __SheetRouteContainerState();
}

class __SheetRouteContainerState extends State<_SheetRouteContainer>
    with TickerProviderStateMixin {
  SheetRoute<dynamic> get route => widget.sheetRoute;
  SheetController get _sheetController => widget.sheetRoute._sheetController;
  AnimationController get _routeController =>
      widget.sheetRoute._routeAnimationController!;
  @override
  void initState() {
    _routeController.addListener(onRouteAnimationUpdate);
    _sheetController.addListener(onSheetExtentUpdate);
    WidgetsBinding.instance.addPostFrameCallback((Duration timeStamp) {
      _sheetController.relativeAnimateTo(
        route.initialExtent,
        duration: route.transitionDuration,
        curve: route.animationCurve ?? Curves.easeOut,
      );
    });
    super.initState();
  }

  @override
  void dispose() {
    _routeController.addListener(onRouteAnimationUpdate);
    _sheetController.removeListener(onSheetExtentUpdate);
    super.dispose();
  }

  void onSheetExtentUpdate() {
    if (_routeController.value != _sheetController.animation.value) {
      if (route.isCurrent &&
          !_firstAnimation &&
          !_sheetController.position.preventingDrag &&
          route.shouldPreventPopForExtent(_sheetController.animation.value) &&
          _sheetController.position.userScrollDirection ==
              ScrollDirection.forward) {
        preventPop();
        return;
      }
      if (!_routeController.isAnimating) {
        final double animationValue =
            _sheetController.animation.value.mapDistance(
          fromLow: 0,
          fromHigh: route.initialExtent,
          toLow: 0,
          toHigh: 1,
        );
        _routeController.value = animationValue;
        if (_sheetController.animation.value == 0) {
          _routeController.value = 0.001;
          _routeController.animateBack(0);
          route.navigator?.pop();
        }
      }
    }
  }

  bool _firstAnimation = true;
  void onRouteAnimationUpdate() {
    if (_routeController.isCompleted) {
      _firstAnimation = false;
    }
    if (!_routeController.isAnimating) {
      return;
    }
    // widget.sheetRoute.navigator!.userGestureInProgressNotifier.value = false;

    if (!_firstAnimation &&
        _routeController.value != _sheetController.animation.value) {
      if (_routeController.status == AnimationStatus.forward) {
        final double animationValue = _routeController.value.mapDistance(
          fromLow: 0,
          fromHigh: 1,
          toLow: _sheetController.animation.value,
          toHigh: 1,
        );
        _sheetController.relativeJumpTo(animationValue);
      } else {
        final double animationValue = _routeController.value.mapDistance(
          fromLow: 0,
          fromHigh: 1,
          toLow: 0,
          toHigh: _sheetController.animation.value,
        );
        _sheetController.relativeJumpTo(animationValue);
      }
    }
  }

  /// Stop current sheet transition and call willPop to confirm/cancel the pop
  @protected
  void preventPop() {
    _sheetController.position.preventDrag();
    _sheetController.position.animateTo(
      _sheetController.position.maxScrollExtent,
      duration: const Duration(milliseconds: 400),
      curve: Curves.easeInOut,
    );

    route.willPop().then(
      (RoutePopDisposition disposition) {
        if (disposition == RoutePopDisposition.pop) {
          _sheetController.relativeAnimateTo(
            0,
            duration: const Duration(milliseconds: 400),
            curve: Curves.easeInOut,
          );
        } else {
          _sheetController.position.stopPreventingDrag();
        }
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    final SheetRoute<dynamic> route = widget.sheetRoute;

    return Semantics(
      scopesRoute: true,
      namesRoute: true,
      label: route.sheetLabel,
      explicitChildNodes: true,
      child: route.buildSheet(
        context,
        Builder(builder: widget.sheetRoute.builder),
      ),
    );
  }
}

extension on double {
  /// Re-maps a number from one range to another.
  ///
  /// A value of fromLow would get mapped to toLow, a value of
  /// fromHigh to toHigh, values in-between to values in-between, etc
  double mapDistance({
    required double fromLow,
    required double fromHigh,
    required double toLow,
    required double toHigh,
  }) {
    final double offset = toLow;
    final double ratio = (toHigh - toLow) / (fromHigh - fromLow);
    return ratio * (this - fromLow) + offset;
  }
}