How do I prevent CTRL & Scroll Wheel / Trackpad Zooming in Flutter Web?

Issue

Problem

If I use CTRL + scroll wheel or pinch to zoom with my trackpad in Chrome (Windows), I see this weird behavior:

Where the Flutter web app is resizing but also leaving behind artifacts.

Use case

If I want to override the scroll to zoom in / trackpad zoom behavior in order to use it in my Flutter web app to zoom in on a canvas for example, this prevents me from doing so. Flutter does not prevent this default behavior, even when I react to zoom gestures.

So how do I prevent this from happening?

Solution

This can simply be prevented using HTML DOM JavaScript:

// This prevents zooming in using CTRL + mouse wheel.
// See https://stackoverflow.com/a/67039291/6509751.
document.addEventListener('wheel', function(e) {
  e.ctrlKey && e.preventDefault();
}, {
  passive: false,
});

Simply add this to the <body> tag of the index.html file of your Flutter web app:

<script>
  // This prevents zooming in using CTRL + mouse wheel.
  // See https://stackoverflow.com/a/67039291/6509751.
  document.addEventListener('wheel', function(e) {
    e.ctrlKey && e.preventDefault();
  }, {
    passive: false,
  });
</script>

Answered By – creativecreatorormaybenot

Answer Checked By – Clifford M. (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *