ScrollController如何检测Scroll的开始,停止和滚动?

Gov*_*iyo 5 dart flutter

我将ScrollController用于SingleChildScrollView小部件,我想在其中检测滚动开始,结束/停止以及何时滚动?

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

scrollController = ScrollController()
      ..addListener(() {
        scrollOffset = _scrollController.offset;
      });
Run Code Online (Sandbox Code Playgroud)

也可以尝试,_scrollController.position.activity.velocity但是对我没有帮助。

也有

_scrollController.position.didEndScroll();
_scrollController.position.didStartScroll();
Run Code Online (Sandbox Code Playgroud)

但是我该如何使用呢?

iPa*_*tel 24

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

只需将您包裹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
               )
)
Run Code Online (Sandbox Code Playgroud)

只需声明方法,例如

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

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

  _onEndScroll(ScrollMetrics metrics) {
    print("Scroll End");
  }
Run Code Online (Sandbox Code Playgroud)

将以特定方式通知您。


The*_*ong 8

不需要NotificationListener,我们可以单独使用滚动控制器。

首先,通过使用注册一个帧后回调WidgetsBinding.instance.addPostFrameCallback以确保到那时滚动控制器已经与滚动视图相关联。我们将在该回调中设置侦听器。

为了收听滚动更新,我们可以使用scrollController.addListener.

为了收听开始和停止滚动,我们可以使用bgScrollCtrl.position.isScrollingNotifier.addListener. 您可以检查以下代码:

WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      scrollCtrl.addListener(() { 
        print('scrolling');
      });
      scrollCtrl.position.isScrollingNotifier.addListener(() { 
        if(!scrollCtrl.position.isScrollingNotifier.value) {
          print('scroll is stopped');
        } else {
          print('scroll is started');
        }
      });
    });
Run Code Online (Sandbox Code Playgroud)

  • 比接受的答案更好的方法。谢谢。 (2认同)