skip to Main Content

I have a scroll listener for hiding and showing the bottom navigation bar, It works perfectly but I discover it will fire the function almost 50 times and more when it meets the condition if I scroll too fast. Which means it will rebuild the widget so many times right? How can I prevent this from happening.

updateBottomBar is a callback function to setstate the parent widget.

bottomBarVisible is the variable to show and hide the bottom nav bar.

 @override
  void initState() {
    scrollController.addListener(() {
      //listener
     
      if (scrollController.position.userScrollDirection ==
              ScrollDirection.reverse &&
          widget.bottomBarVisible == true) {
        print("it is hide");
        widget.updateBottomBar(false);
      } else if (scrollController.position.userScrollDirection ==
              ScrollDirection.forward &&
          widget.bottomBarVisible == false) {
        print("it is show");
        widget.updateBottomBar(true);
      }
    });

2

Answers


  1. I see you are already checking widget.bottomBarVisible == true before setting it to false by calling widget.updateBottomBar(false). So that means, it would only call your function once, right?

    If that’s not the case, maybe you are not updating the bottomBarVisible variable quickly enough. I suggest you update the variable as the first thing to do in your updateBottomBar() function, to prevent rapid firing.

    Login or Signup to reply.
  2. addListener work multiple time while scrolling is not finished. You can handle using atEdge function that will return true when scrolling finished.

    sController.position.atEdge

    sController.addListener(() async {
              if (sController.position.userScrollDirection ==
                  ScrollDirection.reverse && sController.position.atEdge) {
                goNextPage();
              } else if (sController.position.userScrollDirection ==
                  ScrollDirection.forward && sController.position.atEdge) {
                goPreviousPage();
              }
            });
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search