Search code examples
androidflutterzooming

InteractiveViewer image is zoomed in


My problem should be simple, but i'm stuck: i need to display the image of a map with a marker over it (that's why i'm using a stack) and this image can be zoomed and panned. The only problem is, when i open the app the image is totally zoomed in, and i have to zoom out manually. I tried reading the docs and googling but i only found libraries which don't suit my needs or don't work as expected.

So, the question is simple: how can i see the fully zoomed out image from the beginning?

Here's the code.

    return Container(
      height: 350,
      child: InteractiveViewer(
        // TODO the image is automatically zoomed in!
        minScale: .1,
        maxScale: 1,
        constrained: false,
        child: Stack(children: [
          Image.asset(itinerary.mapImage, fit: BoxFit.fitWidth),
          icon(...),
        ])
      )
    )


Solution

  • You need to use a TransformationController to control InteractiveViewer. Here is the code:

      TransformationController _controller;
    
      @override
      void initState() {
        _controller = TransformationController();
        _controller.value = Matrix4.identity() * 0.5;
        super.initState();
      }
    
      @override
      void dispose() {
        _controller.dispose();
        super.dispose();
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text(widget.title),
          ),
          body: Container(
            height: 350,
            child: InteractiveViewer(
              transformationController: _controller,
              minScale: .1,
              maxScale: 1,
              onInteractionEnd: (s) {
                print(_controller.value);
              },
              constrained: false,
              child: Stack(
                children: [
                  Image.asset(
                    "assets/Big.Buck.Bunny.-.Landscape.png",
                    fit: BoxFit.fitWidth,
                  ),
                ],
              ),
            ),
          ),
        );
      }
    

    Please note that you may need to adjust initial scale value(the one multiplying with Matrix4) to get your desired output.