Search code examples
flutterdartscroll

In Flutter how can I execute a function/method when the user starts scrolling?


I have a UI with a list of size-changing widgets. I have their controllers to stop them from changing and make them all with only one size.

I have them being built inside a ListView.builder, so I would like when my user starts scrolling, all of my widgets shrink so I could give the itemExtent parameter to the ListView.builder so the scrolling performs better.


Solution

  • You can use the NotificationListener<ScrollNotification> to watch when your widget is being scrolled. Example:

    return NotificationListener<ScrollNotification>(
          onNotification: (scrollNotification) {
            if (scrollNotification is ScrollStartNotification) {
              // do something when it starts scrolling
            } else if (scrollNotification is ScrollUpdateNotification) {
              // do something else, or nothing
            } else if (scrollNotification is ScrollEndNotification) {
              // do something when it stops scrolling
            }
            return false;
          },
          child: ListView.builder(
            itemCount: 20,
            itemBuilder: (_, index) {
              return ListTile(
                title: Text('Item $index'),
              );
            },
          ),
        );