Search code examples
flutterdartsvggesturedetector

Flutter how to change SVG after onTap with Gesture Detector


Wanna implement same functionality that is done here with images:

Flutter how to change image after onTap with Gesture Detector

Im using this package: https://pub.dev/packages/flutter_svg/example

Even though I'm able to do this in IconButton, I need this in GestureDetector, not in IconButton, so just to be clear, need help how to implement SVG into GestureDetector not IconButton!

I'm able to get SVG rendered on the screen but can't figure it out how to implement it in GestureDetector, to render SVG on screen, Im doing it like this:

Expanded svgTest({double blackKeyWidth}) {
    return Expanded(
      child: Container(
        child: IconButton(
            icon: SvgPicture.asset(
              'assets/images/1.svg',
              fit: BoxFit.fill,
              allowDrawingOutsideViewBox: true,
              width: 500,
            ),
            onPressed: null //do something,
            ),
      ),
    );
  }

Cant figure out how to implement SVG in GestureDetector, it can't go in as Image and Gesture Detector doesn't accept icon, or Im not doing it right.

Thank


Solution

  • If you want to change the image on the onTap method of the iconButton then you should have to change the path of the image in onTap method using setState

    String imagePath = "assets/images/1.svg";
    
    Expanded svgTest({double blackKeyWidth}) {
        return Expanded(
          child: Container(
            child: IconButton(
                icon: SvgPicture.asset(
                  '${imagePath}',
                  fit: BoxFit.fill,
                  allowDrawingOutsideViewBox: true,
                  width: 500,
                ),
                onPressed: (){
                   setState(() {
                      imagePath = "assets/images/2.svg";
                    });
    },
                ),
          ),
        );
      }
    

    EDITED: (For Gesture Detector You Can Simply Wrap the SVG in it)

    Replace the iconbutton with the GestureDetector and Add its onTap and onTapUp methods too.

      GestureDetector(
        onTap: () {
          setState(() {
            imagePath = "assets/images/2.svg";
          });
        },
        onTapUp: (TapUpDetails tapUpDetails) {
          setState(() {
            imagePath = "assets/images/1.svg";
          });
        },
        child: SvgPicture.asset(
          '${imagePath}',
          //fit: BoxFit.fill,
          //allowDrawingOutsideViewBox: true,
          //width: 500,
        ),
      ),
    

    For More About GestureDetector and Flutter SVG Click Here