Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

dart - 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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...