Back to Top

Show FAB While Scrolling Up in Flutter.

Updated 22 December 2023

In this blog, we will implement how to show a Floating Action Button (FAB) while scrolling up in Flutter.

This feature is displayed in the app as we scroll through a list view. This makes our Flutter application more interactive and user-friendly.

You may also check our Flutter app development services.

Let’s Start the code implementation. Import the following library.

import 'package:flutter/rendering.dart';

Creating Scroll View Screen with FAB button:

Step 1: Develop a stateful widget to create a custom floating action button that automatically hides and reveals scroll events.

Start your headless eCommerce
now.
Find out More

Step 2:

Design a screen with a floating action button and a scrolling display, such as a list view or grid view.

import 'package:flutter/material.dart';

void main() {
  runApp(const CustomFabButton());
}

class CustomFabButton extends StatefulWidget {
  const CustomFabButton({Key? key}) : super(key: key);

  @override
  State<CustomFabButton> createState() => _CustomFabButtonState();
}

class _CustomFabButtonState extends State<CustomFabButton> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        appBar: AppBar(title: Text("Custom FAB Example"),),
          floatingActionButton: FloatingActionButton(
              onPressed:(){} ,
              backgroundColor:Colors.blue,
              child:Icon(Icons.arrow_upward,color:Colors.white,),
            ),
        body: ListView.builder(
            itemCount:50 ,
            itemBuilder: (context,index)
            {
              return Card(
                child:ListTile(
                  title:Text("Item $index") ,
                ) ,
              );
            }
        ),
      ),
    );
  }
}

Step 3:

When the user scrolls up the screen, the floating action button app will now appear. The scroll view’s scrolling events need to be monitored. We must assign a unique scroll controller to the scroll view in order for it to hear the scrolling events.

class _CustomFabButtonState extends State<CustomFabButton> {
  ScrollController scrollViewController=ScrollController();
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        appBar: AppBar(title: Text("Custom FAB Example"),),
          floatingActionButton: FloatingActionButton(
              onPressed:(){
                   } ,
               backgroundColor:Colors.blue,
              child:Icon(Icons.arrow_upward,color:Colors.white,),
            ),
        body: ListView.builder(
           controller: scrollViewController,
            itemCount:50 ,
            itemBuilder: (context,index)
            {
              return Card(
                child:ListTile(
                  title:Text("Item $index") ,
                ) ,
              );
            }
        ),
      ),
    );
  }
}

Step 4:

To control the visibility of the FAB, you need to wrap it inside a Visibility widget. This will allow you to show or hide the FAB as needed.
To control when the visibility widget is shown or hidden, you need to create a Boolean variable called “isVisible”.

 floatingActionButton: Visibility(
            visible: isVisible,
            child: FloatingActionButton(
                onPressed:(){
                    },
                backgroundColor:Colors.blue,
                child:Icon(Icons.arrow_upward,color:Colors.white,),
              ),
          ),

Step 5:

Add the Scroll Controller parameter to the CustomFab widget function to listen to widget scroll events.

Add a callback to this scroll controller in the widget’s initState method.

void initState() {
    scrollViewController?.addListener((){
    });
      super.initState();
  }


Now add a condition that when the user scrolls down, set isVisible to false and when the user scrolls up, name isVisible to true.

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

By adding a condition to the callback, we can show or hide the FAB and update the UI with setState. Clicking the button sends the content to the top.

Complete code:

import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';

void main() {
  runApp(const CustomFabButton());
}

class CustomFabButton extends StatefulWidget {
  const CustomFabButton({Key? key}) : super(key: key);

  @override
  State<CustomFabButton> createState() => _CustomFabButtonState();
}

class _CustomFabButtonState extends State<CustomFabButton> {
  ScrollController scrollViewController = ScrollController();
  bool isVisible = false;

  @override
  void initState() {
    scrollViewController?.addListener(() {
      if (scrollViewController?.position.userScrollDirection ==
          ScrollDirection.reverse) {
        if (isVisible == true) {
          setState(() {
            isVisible = false;
          });
        }
      } else {
        if (scrollViewController?.position.userScrollDirection ==
            ScrollDirection.forward) {
          if (isVisible == false) {
            setState(() {
              isVisible = true;
            });
          }
        }
      }
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        appBar: AppBar(
          title: Text("Custom FAB Example"),
        ),
        floatingActionButton: Visibility(
          visible: isVisible,
          child: FloatingActionButton(
            onPressed: () {
               scrollViewController.animateTo(
                    scrollViewController.position.minScrollExtent,
                    duration: const Duration(milliseconds: 200),
                    curve: Curves.ease);
                  },
            backgroundColor: Colors.blue,
            child: const Icon(
              Icons.arrow_upward,
              color: Colors.white,
            ),
          ),
        ),
        body: ListView.builder(
            controller: scrollViewController,
            itemCount: 50,
            itemBuilder: (context, index) {
              return Card(
                child: ListTile(
                  title: Text("Item $index"),
                ),
              );
            }),
      ),
    );
  }
}

Output:

Upon scrolling up, FAB appears while it disappears while scrolling down in the list view. Attached video for reference.

Conclusion

We have finished implementing the feature of showing the FAB while scrolling up in Flutter.

Check here for more interesting blogs – https://mobikul.com/blog/

This blog post provides a clear implementation guide for showing FAB while scrolling up in Flutter.

Thank you for taking the time to read this blog❤️.

References

https://medium.com/@aakashpp/automatic-show-hide-fab-on-scroll-in-flutter-2c0abd94f3da

. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


14 comments

  • Jett
    • sakshirai.mk754 (Moderator)
  • rohan arora
    • sakshirai.mk754 (Moderator)
  • rohan arora
    • sakshirai.mk754 (Moderator)
  • Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home