DEV Community

Aakashp
Aakashp

Posted on • Originally published at Medium

Automatic Show/Hide FAB on scroll in Flutter

Hello readers, Welcome back to another article on flutter.

In this we will see how to hide or show the Floating action button in flutter app when the user scrolls the screen.

Sometimes it is required to hide the FAB button when user scrolls because it blocks the behind view of the screen.

So this is what we want to do today.

Task To Achieve Today

Creating Scroll View
First create a screen with any scrolling view like list view or grid view in it and a Floating action button.

Code

Now to hide the fab on scroll we need to listen to the scrolling events of scroll view.
To listen to the scrolling events we need to give the scroll view a custom scroll controller.
Code
Now we can listen to the scroll events of this list view by add callback to the scroll controller .

Creating Custom FAB
Now create a custom Floating action button which will hide/show automatically based on the scroll event. To do this first create a stateful widget and return FAB in the build method.
Code
Now wrap this FAB inside visibility widget to hide or show the Fab.
Create a Boolean variable isVisible to control the visibility of the visibility widget.

Code

Now in the constructor of this CustomFab widget add a parameter of Scroll Controller. So that we can listen scroll events in this widget.

In the initState method of this widget add a callback to this scroll controller.
Code
Now add a condition that if user scroll down make isVisible to false and if user scrolls up name isVisible to true.

To do this we can use the controller.position.userScrollDirection property of controller. This will give the direction in which the user is scrolling(forward or reverse).

Using this we can add a if condition in callback to show / hide our FAB and update the UI by calling setState.

Code

set the visible parameter of Visibility widget to isVisible.

Code

Another Example
Using similar method we can also achieve something like this with extended Floating action button.

Code

Follow Me

Thanks For reading this article until now, If you liked this than you can also read more articles and follow me.

Aakashp – Medium

Read writing from Aakashp on Medium. Flutter, Java, developer. | Trying to explain concepts in the most straightforward way possible. Every day, Aakashp and thousands of other voices read, write, and share important stories on Medium.

favicon medium.com

aakashp image

Aakashp


Top comments (0)