How to get the value of the current scale of InteractiveViewer in flutter?

Viewed 2945

So what I want to do here is to change the size of a SingleChildScrollView proportionally whenever the scale of the InteractiveViewer. For example: scale 1.0 = width of the scrollview is 1000, scale 2.0 = width of the scrollview is 2000 and so on. I can't seem to find out how to be able to do this directly from the documentation. So I considered it by getting the value of the property(scale) itself and re-render the SingleChildScrollView widget but I can't seem to find any way to do this either. If there is any need for more clarification feel free to ask. Thank you!

3 Answers

You can get the actual and persistent scale value like this:

class InteractiveViewerTest extends StatefulWidget {
  @override
  _InteractiveViewerTestState createState() => _InteractiveViewerTestState();
}

class _InteractiveViewerTestState extends State<InteractiveViewerTest> {
  TransformationController _transformationController =
      TransformationController();

  @override
  Widget build(BuildContext context) {
    return InteractiveViewer(
      minScale: 0.5,
      maxScale: 2.0,
      transformationController: _transformationController,
      onInteractionEnd: (details) {
        // Details.scale can give values below 0.5 or above 2.0 and resets to 1
        // Use the Controller Matrix4 to get the correct scale.
        double correctScaleValue = _transformationController.value.getMaxScaleOnAxis();
      },
      child: Container(
        width: 100,
        height: 100,
        color: Colors.blue,
      ),
    );
  }
}

The onInteractionUpdate is called when the user updates a pan or scale gesture on the widget. So you can get the current scale from the callback.

I added a demo code below:

       InteractiveViewer(
        transformationController: transformationController,
        onInteractionUpdate: (ScaleUpdateDetails details){  // get the scale from the ScaleUpdateDetails callback
          var myScale = details.scale;
          print(myScale); // print the scale here
        },
        boundaryMargin: EdgeInsets.all(20.0),
        minScale: 0.1,
        maxScale: 4.6,
        scaleEnabled: true,
        panEnabled: true,
        child: ClipRRect(
          borderRadius: BorderRadius.circular(18.0),
          child: Image.asset('images/user_picture.png'),
        ),
      );

Use onInteractionUpdate property and get the value from ScaleUpdateDetails like:

double scale;

InteractiveViewer(
  onInteractionUpdate: (details) {
    scale = details.scale; // This is your scale. 
  },
  child: FlutterLogo(),
);
Related