DEV Community

Cristovão Farias
Cristovão Farias

Posted on • Edited on

How to create a similar to Google maps pan an a zoom movement in Flutter flame

Hello everyone, how are you? Here I am with another mini-tutorial that I learned in my day-to-day work. Recently, we needed a camera movement in our app similar to what Google does in Google Maps, and since we are using Flutter and, in conjunction, Flame, there wasn't much material available on this. So, with this challenge in mind, I researched extensively and tested various possibilities until one day I decided to try ScaleDetector and Pandetect from Flame. I discovered that ScaleDetector was nothing more than a superset of PanDetector.

In summary, we were able to create the solution, and here I am to document this code for you.

Note: Remember to check the Flutter Flame documentation to implement everything correctly, using the ScaleDetector mixin.

Flame doc -> https://docs.flame-engine.org/

void clampZoom() {
    camera.viewfinder.zoom = camera.viewfinder.zoom.clamp(0.8, 5);
  }

  static const zoomPerScrollUnit = 0.01;
  late double startZoom;
  @override
  void onScaleStart(info) {
    startZoom = camera.viewfinder.zoom;
  }

  @override
  void onScaleUpdate(ScaleUpdateInfo info) {
    final currentScale = info.scale.global;
    if (!currentScale.isIdentity()) {
      camera.viewfinder.zoom = startZoom * currentScale.y;
      camera.moveBy(info.delta.global);
      clampZoom();
    } else {
      final delta = -info.delta.global;
      camera.moveBy(delta);
    }
  }
Enter fullscreen mode Exit fullscreen mode

I would also like to thank Lukas (@spydon ), who has been doing an excellent job in the development of Flame and its community.

Top comments (5)

Collapse
 
spydon profile image
Lukas Klingsbo

Hey hey, good job! I think there might be a problem with this solution though, I don't think that it will work together with callbacks, like the TapCallbacks or DragCallbacks mixin on some components. Have you tried?

Collapse
 
cristovoxdgm profile image
Cristovão Farias

It doesnt work with DragCallback

Collapse
 
cristovoxdgm profile image
Cristovão Farias

Probably if doesnt work, i will need to do a work around on that, maybe a button to toggle the movement.

Collapse
 
cristovoxdgm profile image
Cristovão Farias

No, i havent, i will try to see if it will work

Collapse
 
cristovoxdgm profile image
Cristovão Farias

It works with tapCallback, i tested it here. I will try with DragCallbacks to see.