Listen to Scroll and stop Mouse Hover events while scrolling - Flutter

45 views Asked by At

I have a SingleChildScrollView with multiple elements inside it. And some of them are MouseRegion widgets. That listens to hover and starts some animation.

But that kinda messes up, when it gets hovered while scrolling down/up on the SingleChildScrollView widget. Now I just want to listen to the scroll state. And don't allow to animate while the use is scrolling.

So far I've tried 2 different ways to do that -

  1. Listen to the ScrollNotification

     onNotification: (notification) {
         if (notification is ScrollStartNotification) {
           _canPoint = false;
         } else if (notification is ScrollUpdateNotification) {
           _canPoint = false;
         } else if (notification is ScrollEndNotification) {
           _canPoint = true;
         }
         return true;
      },
    

    And use the _canPoint variable with a IgnorePointer Widget.

    IgnorePointer(
       ignoring: !_canPoint,
       child: ...(Section that listens to MouseHover),
    ),
    
  2. Check the scroll state of the scrollable of current context. And not forward with the animation based on that.

    _runAnimation() {
       final notifier = Scrollable.of(context).position.isScrollingNotifier;
       if(notifier.value) return;
       //* Continue with the animation.
    }
    

But none of them worked as aspected so far. I was looking for a better way to handle the situation. Thanks in advance.

1

There are 1 answers

2
Yakubu On

Add provider package to pubspec.yaml

define ScrollHoverProvider

class ScrollHoverProvider with ChangeNotifier {
  bool _canAnimate = true;

  bool get canAnimate => _canAnimate;

  void startScrolling() {
    _canAnimate = false;
  notifyListeners();
  }

  void stopScrolling() {
    _canAnimate = true;
    notifyListeners();
   }
}

Wrap your app with the Provider:

void main() {
  runApp(
    ChangeNotifierProvider(
     create: (context) => ScrollHoverProvider(),
     child: MyApp(),
    ),
  );
}



class CustomHover extends StatelessWidget {
  @override
   Widget build(BuildContext context) {
   // Access the provider
   final provider = Provider.of<ScrollHoverProvider>(context);

   return MouseRegion(
     onEnter: (event) {
      if (provider.canAnimate) {
       // Trigger hover animation
       }
      },
        child: Container(
        // Your widget code
      ),
    );
  }
}