Reputation: 135
How to disable the context menu in Flutter (2.x, Web / Browser) when e.g. right click or in touch long press on mobile devices (e.g. DevTools mobile view).
I come from web development with Angular etc. In HTML/JS it works like:
document.body.addEventListener('contextmenu', (event) => {
event.preventDefault();
});
But how to do this on Flutter? Is there contextmenu event which can be disabled. Blocking right click will not work. Because it also appears on mobile long press (on release).
Upvotes: 7
Views: 3534
Reputation: 61
import 'package:flutter/services.dart';
void main() {
WidgetsFlutterBinding.ensureInitialized();
if (kIsWeb) {
BrowserContextMenu.disableContextMenu();
}
runApp(const MyApp());
}
Upvotes: 2
Reputation: 117
Has you can see here: https://api.flutter.dev/flutter/widgets/ContextMenuController-class.html
You can use: BrowserContextMenu.disableContextMenu();
But be careful, this returns a future
Upvotes: 3
Reputation: 5675
You could just add a script to web\index.html
in your project.
<script>
document.body.addEventListener('contextmenu', (event) => {
event.preventDefault();
});
</script>
After this change, debug mode should be restarted. Tested with Flutter 3.3.
Avoid import 'dart:html'
in a cross-platform project/context. Flutter will also warn you.
Upvotes: 2
Reputation: 181
That works for me!
For first:
import 'dart:html' as html;
And after this init this code to prevent right-click mouse for showing context menu.
html.document.body!
.addEventListener('contextmenu', (event) => event.preventDefault());
In my project, it works on version Flutter 2.2.3 • channel stable.
Upvotes: 2
Reputation: 135
Currently there is no official solution. Here is the related GitHub issue: flutter#78671.
Workaround: Just open the dev tools of the browser and execute the following code in the console:
document.body.addEventListener('contextmenu', (event) => {
event.preventDefault();
});
The hot reload from Flutter does not reload the page. So it will work for the whole session.
Upvotes: 3