physics.dart 17.3 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 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531
import 'dart:math' as math;

import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';

/// {@template flutter.widgets.sheet.physics}
/// Determines the physics of a [Sheet] widget.
///
/// For example, determines how the [Sheet] will behave when the user
/// reaches the maximum drag extent or when the user stops dragging.
/// {@endtemplate}
mixin SheetPhysics on ScrollPhysics {
  bool shouldReload(covariant ScrollPhysics old) => false;
}

/// Sheet physics that does not allow the user to drag a sheet.
class NeverDraggableSheetPhysics extends NeverScrollableScrollPhysics
    with SheetPhysics {
  const NeverDraggableSheetPhysics({super.parent});

  @override
  NeverDraggableSheetPhysics applyTo(ScrollPhysics? ancestor) {
    return NeverDraggableSheetPhysics(parent: buildParent(ancestor));
  }
}

/// Sheet physics that always lets the user to drag a sheet.
class AlwaysDraggableSheetPhysics extends AlwaysScrollableScrollPhysics
    with SheetPhysics {
  /// Creates scroll physics that always lets the user scroll.
  const AlwaysDraggableSheetPhysics({super.parent});

  @override
  AlwaysDraggableSheetPhysics applyTo(ScrollPhysics? ancestor) {
    return AlwaysDraggableSheetPhysics(parent: buildParent(ancestor));
  }
}

/// Creates sheet physics that bounce back from the edge.
class BouncingSheetPhysics extends ScrollPhysics with SheetPhysics {
  /// Creates sheet physics that bounce back from the edge.
  const BouncingSheetPhysics({
    super.parent,
    this.overflowViewport = false,
  });

  final bool overflowViewport;

  @override
  BouncingSheetPhysics applyTo(ScrollPhysics? ancestor) {
    return BouncingSheetPhysics(
        parent: buildParent(ancestor), overflowViewport: overflowViewport);
  }

  @override
  bool shouldReload(covariant ScrollPhysics old) {
    return old is BouncingSheetPhysics &&
        old.overflowViewport != overflowViewport;
  }

  /// The multiple applied to overscroll to make it appear that scrolling past
  /// the edge of the scrollable contents is harder than scrolling the list.
  /// This is done by reducing the ratio of the scroll effect output vs the
  /// scroll gesture input.
  ///
  /// This factor starts at 0.52 and progressively becomes harder to overscroll
  /// as more of the area past the edge is dragged in (represented by an increasing
  /// `overscrollFraction` which starts at 0 when there is no overscroll).
  double frictionFactor(double overscrollFraction) =>
      0.1 * math.pow(1 - overscrollFraction, 4);

  @override
  double applyPhysicsToUserOffset(ScrollMetrics position, double offset) {
    assert(offset != 0.0);
    assert(position.minScrollExtent <= position.maxScrollExtent);

    if (!position.outOfRange) {
      return offset;
    }

    final double overscrollPastStart =
        math.max(position.minScrollExtent - position.pixels, 0.0);
    final double overscrollPastEnd =
        math.max(position.pixels - position.maxScrollExtent, 0.0);
    final double overscrollPast =
        math.max(overscrollPastStart, overscrollPastEnd);
    final bool easing = (overscrollPastStart > 0.0 && offset < 0.0) ||
        (overscrollPastEnd > 0.0 && offset > 0.0);

    final double friction = easing
        // Apply less resistance when easing the overscroll vs tensioning.
        ? frictionFactor(
            (overscrollPast - offset.abs()) / position.viewportDimension)
        : frictionFactor(overscrollPast / position.viewportDimension);
    final double direction = offset.sign;

    return direction * _applyFriction(overscrollPast, offset.abs(), friction);
  }

  static double _applyFriction(
    double extentOutside,
    double absDelta,
    double gamma,
  ) {
    assert(absDelta > 0);
    double total = 0.0;
    if (extentOutside > 0) {
      final double deltaToLimit = extentOutside / gamma;
      if (absDelta < deltaToLimit) {
        return absDelta * gamma;
      }
      total += extentOutside;
      absDelta -= deltaToLimit;
    }
    return total + absDelta;
  }

  @override
  double applyBoundaryConditions(ScrollMetrics position, double value) {
    assert(() {
      if (value == position.pixels) {
        throw FlutterError.fromParts(<DiagnosticsNode>[
          ErrorSummary(
              '$runtimeType.applyBoundaryConditions() was called redundantly.'),
          ErrorDescription(
            'The proposed new position, $value, is exactly equal to the current position of the '
            'given ${position.runtimeType}, ${position.pixels}.\n'
            'The applyBoundaryConditions method should only be called when the value is '
            'going to actually change the pixels, otherwise it is redundant.',
          ),
          DiagnosticsProperty<ScrollPhysics>(
              'The physics object in question was', this,
              style: DiagnosticsTreeStyle.errorProperty),
          DiagnosticsProperty<ScrollMetrics>(
              'The position object in question was', position,
              style: DiagnosticsTreeStyle.errorProperty),
        ]);
      }
      return true;
    }());
    if (!overflowViewport) {
      // overscroll
      if (position.viewportDimension <= position.pixels &&
          position.pixels < value) {
        return value - position.pixels;
      }
      // hit top edge
      if (value < position.viewportDimension &&
          position.viewportDimension < position.pixels) {
        return value - position.viewportDimension;
      }
    }
    // underscroll
    if (value < position.pixels &&
        position.pixels <= position.minScrollExtent) {
      return value - position.pixels;
    }
    // hit bottom edge
    if (position.pixels < position.maxScrollExtent &&
        position.maxScrollExtent < value) {
      return value - position.maxScrollExtent;
    }
    return 0.0;
  }

  @override
  Simulation? createBallisticSimulation(
      ScrollMetrics position, double velocity) {
    if (position.outOfRange) {
      return BouncingScrollSimulation(
        spring: const SpringDescription(
          mass: 1.2,
          stiffness: 200.0,
          damping: 25,
        ),
        position: position.pixels,
        velocity: velocity,
        leadingExtent: position.minScrollExtent,
        trailingExtent: position.maxScrollExtent,
        tolerance: toleranceFor(position),
      );
    }
    return super.createBallisticSimulation(position, velocity);
  }

  // The ballistic simulation here decelerates more slowly than the one for
  // ClampingScrollPhysics so we require a more deliberate input gesture
  // to trigger a fling.
  @override
  double get minFlingVelocity => kMinFlingVelocity * 2.0;

  // Methodology:
  // 1- Use https://github.com/flutter/platform_tests/tree/master/scroll_overlay to test with
  //    Flutter and platform scroll views superimposed.
  // 3- If the scrollables stopped overlapping at any moment, adjust the desired
  //    output value of this function at that input speed.
  // 4- Feed new input/output set into a power curve fitter. Change function
  //    and repeat from 2.
  // 5- Repeat from 2 with medium and slow flings.
  /// Momentum build-up function that mimics iOS's scroll speed increase with repeated flings.
  ///
  /// The velocity of the last fling is not an important factor. Existing speed
  /// and (related) time since last fling are factors for the velocity transfer
  /// calculations.
  @override
  double carriedMomentum(double existingVelocity) {
    return existingVelocity.sign *
        math.min(0.000816 * math.pow(existingVelocity.abs(), 1.967).toDouble(),
            40000.0);
  }

  // Eyeballed from observation to counter the effect of an unintended scroll
  // from the natural motion of lifting the finger after a scroll.
  @override
  double get dragStartDistanceMotionThreshold => 3.5;
}

/// Creates sheet physics that has no momentum after the user stops dragging.
class NoMomentumSheetPhysics extends ScrollPhysics with SheetPhysics {
  /// Creates sheet physics that has no momentum after the user stops dragging.
  const NoMomentumSheetPhysics({
    super.parent,
  });

  @override
  NoMomentumSheetPhysics applyTo(ScrollPhysics? ancestor) {
    return NoMomentumSheetPhysics(parent: buildParent(ancestor));
  }

  @override
  double applyBoundaryConditions(ScrollMetrics position, double value) {
    // underscroll
    if (value < position.pixels &&
        position.pixels <= position.minScrollExtent) {
      return value - position.pixels;
    }
    if (position.maxScrollExtent <= position.pixels &&
        position.pixels < value) {
      // overscroll
      return value - position.pixels;
    }
    if (value < position.minScrollExtent &&
        position.minScrollExtent < position.pixels) {
      // hit top edge
      return value - position.minScrollExtent;
    }
    if (position.pixels < position.maxScrollExtent &&
        position.maxScrollExtent < value) {
      // hit bottom edge
      return value - position.maxScrollExtent;
    }
    return 0.0;

    // if (position.viewportDimension <= position.pixels &&
    //     position.pixels < value) // hit top edge
    //   return value - position.pixels;
    // if (position.pixels < 0 && position.pixels > value) // hit bottom edge
    //   return value - position.pixels;
    // return 0.0;
  }

  @override
  Simulation? createBallisticSimulation(
      ScrollMetrics position, double velocity) {
    if (position.outOfRange) {
      double? end;
      if (position.pixels > position.maxScrollExtent) {
        end = position.maxScrollExtent;
      } else if (position.pixels < position.minScrollExtent) {
        end = position.minScrollExtent;
      }
      assert(end != null);
      return ScrollSpringSimulation(
        spring,
        position.pixels,
        end!,
        math.min(0.0, velocity),
        tolerance: toleranceFor(position),
      );
    }
    return null;
  }
}

class ClampingSheetPhysics extends ScrollPhysics with SheetPhysics {
  /// Creates sheet physics that has no momentum after the user stops dragging.
  const ClampingSheetPhysics({
    super.parent,
  });

  @override
  ClampingSheetPhysics applyTo(ScrollPhysics? ancestor) {
    return ClampingSheetPhysics(parent: buildParent(ancestor));
  }

  @override
  double applyBoundaryConditions(ScrollMetrics position, double value) {
    assert(() {
      if (value == position.pixels) {
        throw FlutterError.fromParts(<DiagnosticsNode>[
          ErrorSummary(
              '$runtimeType.applyBoundaryConditions() was called redundantly.'),
          ErrorDescription(
            'The proposed new position, $value, is exactly equal to the current position of the '
            'given ${position.runtimeType}, ${position.pixels}.\n'
            'The applyBoundaryConditions method should only be called when the value is '
            'going to actually change the pixels, otherwise it is redundant.',
          ),
          DiagnosticsProperty<ScrollPhysics>(
              'The physics object in question was', this,
              style: DiagnosticsTreeStyle.errorProperty),
          DiagnosticsProperty<ScrollMetrics>(
              'The position object in question was', position,
              style: DiagnosticsTreeStyle.errorProperty),
        ]);
      }
      return true;
    }());
    // hit top edge
    if (position.viewportDimension <= position.pixels &&
        position.pixels < value) {
      return value - position.pixels;
    }
    // hit bottom edge
    if (position.pixels < 0 && position.pixels > value) {
      return value - position.pixels;
    }
    return 0.0;
  }

  @override
  Simulation? createBallisticSimulation(
      ScrollMetrics position, double velocity) {
    final Tolerance tolerance = toleranceFor(position);
    if (position.outOfRange) {
      double? end;
      if (position.pixels > position.maxScrollExtent) {
        end = position.maxScrollExtent;
      }
      if (position.pixels < position.minScrollExtent) {
        end = position.minScrollExtent;
      }
      assert(end != null);
      return ScrollSpringSimulation(
        spring,
        position.pixels,
        end!,
        math.min(0.0, velocity),
        tolerance: tolerance,
      );
    }
    if (velocity.abs() < tolerance.velocity) {
      return null;
    }
    if (velocity > 0.0 && position.pixels >= position.maxScrollExtent) {
      return null;
    }
    if (velocity < 0.0 && position.pixels <= position.minScrollExtent) {
      return null;
    }
    return ClampingScrollSimulation(
      position: position.pixels,
      velocity: velocity,
      tolerance: tolerance,
    );
  }
}

/// Creates snapping physics for a [Sheet].
///
/// When the user stops dragging, the sheet will be snapped to one
/// of closest value inside the [stops] list
///
/// If [relative] is true, this values must be between 0 and 1, where
/// 0 represent the sheet totally hidden and 1 fully visible.
///
/// If [relative] is false, the values are real pixels and will be clamped
/// to [Sheet.minExtent] and [Sheet.maxExtent]
///
class SnapSheetPhysics extends ScrollPhysics with SheetPhysics {
  /// Creates snapping physics for a [Sheet].
  const SnapSheetPhysics({
    super.parent,
    this.stops = const <double>[],
    this.relative = true,
  });

  /// Positions where the sheet could be snapped once the user stops
  /// dragging
  final List<double> stops;

  /// If [relative] is true, this values must be between 0 and 1, where
  /// 0 represent the sheet totally hidden and 1 fully visible.
  ///
  /// If [relative] is false, the values are real pixels and will be clamped
  /// to [Sheet.minExtent] and [Sheet.maxExtent]
  ///
  /// The default values is `false`
  final bool relative;

  @override
  SnapSheetPhysics applyTo(ScrollPhysics? ancestor) {
    return SnapSheetPhysics(
      parent: buildParent(ancestor),
      stops: stops,
      relative: relative,
    );
  }

  @override
  bool shouldReload(covariant ScrollPhysics old) {
    return old is SnapSheetPhysics &&
        (old.relative != relative || !listEquals(old.stops, stops));
  }

  @override
  double adjustPositionForNewDimensions(
      {required ScrollMetrics oldPosition,
      required ScrollMetrics newPosition,
      required bool isScrolling,
      required double velocity}) {
    final Tolerance tolerance = toleranceFor(newPosition);
    return _getTargetPixels(newPosition, tolerance, velocity);
  }

  double _getTargetPixels(
      ScrollMetrics position, Tolerance tolerance, double velocity) {
    int page = _getPage(position) ?? 0;

    final double targetPixels =
        getPixelsFromPage(position, page.clamp(0, stops.length - 1));

    if (targetPixels > position.pixels && velocity < -tolerance.velocity) {
      page -= 1;
    } else if (targetPixels < position.pixels &&
        velocity > tolerance.velocity) {
      page += 1;
    }

    return getPixelsFromPage(position, page.clamp(0, stops.length - 1));
  }

  @override
  Simulation? createBallisticSimulation(
      ScrollMetrics position, double velocity) {
    // If we're out of range and not headed back in range, defer to the parent
    // ballistics, which should put us back in range at a page boundary.
    // if ((velocity <= 0.0 && position.pixels <= position.minScrollExtent) ||
    //     (velocity >= 0.0 && position.pixels >= position.maxScrollExtent))
    //   return super.createBallisticSimulation(position, velocity);
    final Tolerance tolerance = toleranceFor(position);
    final double target = _getTargetPixels(position, tolerance, velocity);
    if (target != position.pixels) {
      return ScrollSpringSimulation(
        const SpringDescription(damping: 25, stiffness: 200, mass: 1.2),
        position.pixels,
        target,
        velocity.clamp(-200, 200),
        tolerance: tolerance,
      );
    }
    return null;
  }

  @override
  bool get allowImplicitScrolling => false;

  int getPageFromPixels(double pixels, double extent) {
    final double actual = math.max(0.0, pixels) / math.max(1.0, extent);
    final int round = _nearestStopForExtent(actual);
    //final double round = actual.roundToDouble();
    if ((actual - round).abs() < precisionErrorTolerance) {
      return round;
    }
    return round;
  }

  int _nearestStopForExtent(double extent) {
    if (stops.isEmpty) {
      return 0;
    }
    final int stop = stops.asMap().entries.reduce(
      (MapEntry<int, double> prev, MapEntry<int, double> curr) {
        return (curr.value - extent).abs() < (prev.value - extent).abs()
            ? curr
            : prev;
      },
    ).key;
    return stop;
  }

  double extentFor(ScrollMetrics position) {
    if (relative) {
      return position.maxScrollExtent;
    }
    return 1;
  }

  double getPixelsFromPage(ScrollMetrics position, int page) {
    if (stops[page].isInfinite) {
      return position.maxScrollExtent;
    }
    return stops[page] * extentFor(position);
  }

  int? _getPage(ScrollMetrics position) {
    assert(
      !position.hasPixels || position.hasContentDimensions,
      'Page value is only available after content dimensions are established.',
    );
    return !position.hasPixels
        ? null
        : getPageFromPixels(
            position.pixels
                .clamp(position.minScrollExtent, position.maxScrollExtent),
            extentFor(position),
          );
  }
}

/// Describes how [SheetScrollable] widgets should behave.
class SheetBehavior extends ScrollBehavior {
  static const SheetPhysics _clampingPhysics =
      NoMomentumSheetPhysics(parent: RangeMaintainingScrollPhysics());

  @override
  SheetPhysics getScrollPhysics(BuildContext context) {
    return _clampingPhysics;
  }
}