Dani S.
Dani S.

Reputation: 131

Flutter web GestureDetector: detect mouse wheel events

I am developing a flutter app for web, and I am trying to execute a callback method when I scroll the mouse wheel inside a widget (which is not a scrolling widget).

I am aware of the MouseRegion widget, and using a Listener as its child I can detect onPointerSignal events. This works fine when the Listener's child is a scrollable widget, such a ListView, but it does not work if this widget is not scrollable.

What I ideally would like to have is a widget similar to GestureDetector, with callback methods that are similar to onPanStart, onPanUpdate and onPanEnd, but instead happening on mouse wheel events (or, in the same way, for trackpad scrolling events on laptops).

Anybody knows how can I achieve this?

Upvotes: 9

Views: 6438

Answers (1)

hacker1024
hacker1024

Reputation: 3668

Listener does not need any parent. A widget like the following can be used, which wraps its child in a Listener and calls the given callback when a PointerScrollEvent is received:

class ScrollDetector extends StatelessWidget {
  final void Function(PointerScrollEvent event) onPointerScroll;
  final Widget child;

  const ScrollDetector({
    Key key,
    @required this.onPointerScroll,
    @required this.child,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Listener(
      onPointerSignal: (pointerSignal) {
        if (pointerSignal is PointerScrollEvent) onPointerScroll(pointerSignal);
      },
      child: child,
    );
  }
}

Here's a complete example on DartPad.

Upvotes: 11

Related Questions