Search code examples
flutterdartflutter-windows

Disable default right click on web in flutter


I'm trying to use my own showMenu when user right click with the mouse on web, windows, macOS and long press on android and iOS.

Long press on android and iOS is working and right click on Windows and macOS is working but having issue to prevent default web right click options.

Btw I've tried this solution but when I try to build for platforms rather than web it's not working as in this we are importing html.

import 'dart:html';

  window.document.onContextMenu.listen((evt) => evt.preventDefault());

I've tried with listener like below and it's working perfectly for MacOs and Windows.

Listener(
       onPointerDown: _onPointerDown ,
       child: ....
)

tried with GestureDetector but not working

GestureDetector(
          onSecondaryTapDown: (details) =>_onPointerDown,
          child: ........
    )

Here is the method which displaying menu named as _onPointDown

Future<void> _onPointerDown(PointerDownEvent event) async {
    if (event.kind == PointerDeviceKind.mouse &&
        event.buttons == kSecondaryMouseButton) {
            ....... //I've added show menu code here
    }
  }

Give me your valuable suggestions and help me to solve my issue. Thank you so much in advance.


Solution

  • So, what I want to do was disable right click of web when I have my own right click menu and enable default one again after my right click is done so, they can use default for copy, paste and do other stuff and I don't have to right that again and again.

    Here is the solution:

    Declare a variable:

    StreamSubscription<MouseEvent>? contextMenuListener;
    

    create a method which will disableRightClick

    void disableRightClick() {
        if (kIsWeb) {
          contextMenuListener = uni.document.onContextMenu.listen((event) => event.preventDefault());
        }
      }
    

    create a method which will enableRightClick

    void enableRightClick() {
        if (kIsWeb) {
          contextMenuListener.cancel();
        }
      }
    

    Call those method like below..

    void customRightClick() {
       disableRightClick();
       .......
       //Create your custom click
       .......
       enableRightClick();
    }
    

    NOTE: Make sure to use same variable for disable and enable