Brendon Cheung
Brendon Cheung

Reputation: 1025

Animating Floating Action Button in Flutter

I'm trying to add in an animated where when the user scrolls down, the fab will animated out and disappear, and when scroll up, the fab reappear again.

Here is my code:

return Scaffold(
      floatingActionButton: AnimatedContainer(
        curve: Curves.easeIn,
        duration: const Duration(seconds: 1),
        child: Opacity(
          opacity: _fabVisible ? 1 : 0,
          child: FloatingActionButton(
            onPressed: () {},
            child: Icon(
              Icons.add,
              color: Colors.black,
            ),
            backgroundColor: Colors.white,
          ),
        ),
      ),

What the code is doing now is the fab is hiding properly, but it doesn't animate the opacity, it just pop in and out without animation, please help!

thank you

Upvotes: 0

Views: 2475

Answers (1)

Jim
Jim

Reputation: 7601

try to use scrollnotification for detecting scroll down (increase of pixels) and scroll up (decrease of pixels), when scroll down, setState _fabVisible = 0, vice versa:

Expanded(
            child: 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: ListView.builder(
                itemCount: 30,
                itemBuilder: (context, index) {
                  return ListTile(title: Text("Index : $index"));
                },
              ),
            ),
          ),

_onStartScroll(ScrollMetrics metrics) {
      setState(() {
        message = "Scroll Start";
      });
    }
_onUpdateScroll(ScrollMetrics metrics) {
      setState(() {
        message = "Scroll Update";
      });
    }
_onEndScroll(ScrollMetrics metrics) {
      setState(() {
        message = "Scroll End";
      });
    }

Upvotes: 1

Related Questions