Trigger Animation based on the scroll events

Imagine a scenario where you want to hide some widgets when the user scrolls up/down with some in/out animations. In this case, you don’t want to check every time the user scrolls instead what you might want is a way to know if the user starts/stopped scrolling.

Luck for us, there is no better widget for this than NotificationListener . Notification Listener is another widget provided by Flutter which allows you to wrap a scrollable . It allows us to listen for ScrollNotifications whenever the scrollable is scrolled.

Example: Hide widgets(AppBar, FAB, and BottomAppBar) when the user is scrolling and show them when they stop:

Hide Widgets when the user is scrolling and show them when he stops

Step 1: Setup Layout

NOTES:

Using PreferredSize in the appBar is required otherwise you should create your custom appBar I used FittedBox just to avoid some scaling issues while animating. Delete it and you will see. that the Icon in the FAB will not scale

Step 2: Setup Animation

The boilerplate is really simple but just to be clear, I am going to use a Tween(begin: 0.0, end: 50.0) for the animation object and change the hardcoded value of 50.0 in all the previous code to use aniamtion.value instead:

And if you are asking why I am using PreferredSize here the answer is simple you can’t edit the default AppBar height without making a custom one, and for the bottomNavigationBar you can use any widget.

Step 3: Listen to Scroll Notifications

Wrap the ListView with NotificationListener of Type ScrollStartNotification and another one for ScrollEndNotification

Let me explain: If the user starts scrolling then the animation is reversed which means hide the widgets or make them smaller so they will become invisible. If the user stops moving then we show the widgets again by playing the animation.

The previous example is good but it’s not good UI practice. Let’s implement a common UI pattern, a “Showing back-to-top” button for when the user is scrolling down.

In this example, we will do the same Step 1 and 2 from the previous example, however, we will make some changes to step 3:

We use ScrollUpdateNotification to get the scrollDelta . This allows us to decide the direction in which the user is scrolling while also making it easier for us to inverse the effect. For example, if you want to show the widget's if the user is scrolling down just inverse the condition from notification.scrollDelta < 0 to notification.scrollDelta > 0 and vice versa for the other condition.

If you don’t like this method, an alternative would be to listen to UserScrollNotification to obtain the ScrollDirection . If the user stops scrolling you will get a ScrollDirection.idle

Important note on ScrollNotification

Don’t drive your layout based on ScrollUpdateNotifications. When the notification is received, the layout phase is already complete. However, you can still do painting effects since painting happens after layout.