Search code examples
fluttergesture

Is there a way to distinguish between left and right mouse pan in Flutter?


Is there a way in which I can distinguish between left button and right button panning in flutter?

I am using a GestureDetector with an onPanUpdate callback. However the details (PanDown/Update/EndDetails) of the function do not have details about the buttons that are being pressed (Thus used to pan). One possible workaround I found is to cache the point using a Listener:

return Listener(
      onPointerDown: (event) => _cachedPointerDownEvent = event,
      child: GestureDetector(
        onPanDown: (details) {},
        onPanStart: (details) {},
        onPanUpdate: (details) {
          switch(_cachedPointerDownEvent!.buttons){
            ...
          }
        },
        onPanEnd: (details) {},
        child: Container(
            color: Colors.red,
            ),
      ),
    );

However this is not too elegant and does not integrate well with other imput methods (trackpad,etc).

I also tried a Listener with the onPointerMove callbacks but the Listener always fires even when another listener is visually in front of it (Flutter - how to ignore parent touch event on child touch event?).

Is there a way to have details about the pointer used for the drag or to have different event for different mouse buttons?


Solution

  • You can achieve the functionality by using a RawGestureRecognizer and configuring it as needed by your use case:

    return RawGestureDetector(
      gestures: {
        /// The type of gesture recognizer to add.
        PanGestureRecognizer:
            GestureRecognizerFactoryWithHandlers<PanGestureRecognizer>(
          () => PanGestureRecognizer(
            /// Change this condition to match the buttons you want to allow.
            allowedButtonsFilter: (buttons) => buttons == kSecondaryButton,
          ),
          (instance) {
            /// Add your event handlers here.
            instance
              ..onDown = (details) {
                log("onDown: $details");
              }
              ..onUpdate = (details) {
                log("onUpdate: $details");
              };
          },
        ),
      },
      child: YourWidget(),
    );