首页 > 解决方案 > ScrollController 如何检测滚动开始、停止和滚动?

问题描述

我正在将 ScrollController 用于SingleChildScrollView要检测滚动开始、结束/停止和仍在滚动的小部件?

我如何检测,我正在使用Listene

scrollController = ScrollController()
      ..addListener(() {
        scrollOffset = _scrollController.offset;
      });

也尝试_scrollController.position.activity.velocity但没有帮助我。

还有

_scrollController.position.didEndScroll();
_scrollController.position.didStartScroll();

但是我该如何使用它呢?

标签: dartflutter

解决方案


从这个链接 https://medium.com/@diegoveloper/flutter-lets-know-the-scrollcontroller-and-scrollnotification-652b2685a4ac

只需将您的 to 包装SingleChildScrollView起来NotificationListener并更新您的代码,例如 ..

NotificationListener<ScrollNotification>(
                onNotification: (scrollNotification) {
                  if (scrollNotification is ScrollStartNotification) {
                    _onStartScroll(scrollNotification.metrics);
                  } else if (scrollNotification is ScrollUpdateNotification) {
                    _onUpdateScroll(scrollNotification.metrics);
                  } else if (scrollNotification is ScrollEndNotification) {
                    _onEndScroll(scrollNotification.metrics);
                  }
                },
                child: SingleChildScrollView(
                /// YOUR OWN CODE HERE
               )
)

只需声明类似的方法

_onStartScroll(ScrollMetrics metrics) {
    print("Scroll Start");
  }

  _onUpdateScroll(ScrollMetrics metrics) {
    print("Scroll Update");
  }

  _onEndScroll(ScrollMetrics metrics) {
    print("Scroll End");
  }

您将通过特定方法收到通知。


推荐阅读