Flutter:如何在页面视图中禁用向左滚动?

Flutter: how to disable the scroll to the left in pageview?

今天,当我开发我的应用程序时,我发现我需要一个功能,它只能允许用户滚动到 right 页面,而不是 left 页面,PageController 没有提供任何可以让我实现它的功能,所以这就是我来这里的原因!

我也去过这个link:

,但它没有包含任何解释,你知道用别人的代码而不知道它在做什么是很痛苦的,对吧?所以请帮帮我!!! ^_^

您可以创建自己的 ScrollPhysics 来将滚动锁定到一个方向,或者您可以使用 horizontal_blocked_scroll_physics 库来帮助您。

这是一个 CustomScrollPhysic 的示例,它只允许向右滚动

class CustomScrollPhysics extends ScrollPhysics {
  CustomScrollPhysics({ScrollPhysics parent}) : super(parent: parent);

  bool isGoingLeft = false;

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

  @override
  double applyPhysicsToUserOffset(ScrollMetrics position, double offset) {
    isGoingLeft = offset.sign < 0;
    return offset;
  }

  @override
  double applyBoundaryConditions(ScrollMetrics position, double value) {
    assert(() {
      if (value == position.pixels) {
        throw FlutterError(
          '$runtimeType.applyBoundaryConditions() was called redundantly.\n'
          '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.\n'
          'The physics object in question was:\n'
          '  $this\n'
          'The position object in question was:\n'
          '  $position\n');
      }
      return true;
    }());
    if (value < position.pixels && position.pixels <= position.minScrollExtent)
      return value - position.pixels;
    if (position.maxScrollExtent <= position.pixels && position.pixels < value)
      return value - position.pixels;
    if (value < position.minScrollExtent &&
        position.minScrollExtent < position.pixels)

      return value - position.minScrollExtent;

    if (position.pixels < position.maxScrollExtent &&
        position.maxScrollExtent < value)
      return value - position.maxScrollExtent;

    if (!isGoingLeft) {
      return value - position.pixels;
    }
    return 0.0;
  }
}

您可以使用下面的示例,CustomScrollPhysics 作为物理参数的值。

PageView.builder(
  physics: CustomScrollPhysics(),
);

一些可以更好地解释 ScrollPhysics 工作原理的参考资料