Nilima
Nilima

Reputation: 53

Flutter: How to add a zoom functionality to image

In my flutter app, a custom image is built with the following code

customImage.dart

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';

Widget cachedNetworkImage(mediaUrl) {
  return CachedNetworkImage(
    imageUrl: mediaUrl,
    fit: BoxFit.cover,
    placeholder: (context, url)=>
    Padding(padding: EdgeInsets.all(20.0),
    child: CircularProgressIndicator(),
    ),
    errorWidget: (context, url, error) => Icon(Icons.error) ,
  );
}

I want to add a functionality to pinch to zoom on this image,how can I achieve that?

Upvotes: 1

Views: 2832

Answers (2)

Ugurcan Yildirim
Ugurcan Yildirim

Reputation: 6142

Use photo_view for this. It allows you to create zoomable image widgets without dealing with pinch gesture or sth.

import 'package:photo_view/photo_view.dart';

@override
Widget build(BuildContext context) {
  return Container(
    child: PhotoView(
      imageProvider: AssetImage("assets/image.jpg"),
    )
  );
}

Source: https://pub.dev/packages/photo_view

Upvotes: 0

chunhunghan
chunhunghan

Reputation: 54407

You can copy paste run full code below
You can use Flutter's bulid-in InteractiveViewer https://api.flutter.dev/flutter/widgets/InteractiveViewer-class.html
A widget that enables pan and zoom interactions with its child.

working demo

enter image description here

full code

import 'package:flutter/material.dart';
import 'package:cached_network_image/cached_network_image.dart';

Widget cachedNetworkImage(mediaUrl) {
  return CachedNetworkImage(
    imageUrl: mediaUrl,
    fit: BoxFit.cover,
    placeholder: (context, url) => Padding(
      padding: EdgeInsets.all(20.0),
      child: CircularProgressIndicator(),
    ),
    errorWidget: (context, url, error) => Icon(Icons.error),
  );
}

void main() => runApp(MyApp());

/// This Widget is the main application widget.
class MyApp extends StatelessWidget {
  static const String _title = 'Flutter Code Sample';

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: _title,
      home: Scaffold(
        appBar: AppBar(title: const Text(_title)),
        body: MyStatelessWidget(),
      ),
    );
  }
}

/// This is the stateless widget that the main application instantiates.
class MyStatelessWidget extends StatelessWidget {
  MyStatelessWidget({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Center(
      child: InteractiveViewer(
        boundaryMargin: EdgeInsets.all(20.0),
        minScale: 0.1,
        maxScale: 1.6,
        child: cachedNetworkImage("https://picsum.photos/250?image=9"),
      ),
    );
  }
}

Upvotes: 2

Related Questions