首页 > 解决方案 > Flutter 如何在 onTap 后使用 Gesture Detector 更改 SVG

问题描述

想要实现与图像相同的功能:

颤振如何使用手势检测器在 onTap 后更改图像

我正在使用这个包: https ://pub.dev/packages/flutter_svg/example

即使我能够在 IconButton 中执行此操作,我也需要在 GestureDetector 中,而不是在 IconButton 中,所以为了清楚起见,需要帮助如何将 SVG 实现为 GestureDetector 而不是 IconButton!

我能够在屏幕上渲染 SVG,但无法弄清楚如何在 GestureDetector 中实现它,在屏幕上渲染 SVG,我这样做是这样的:

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,
            ),
      ),
    );
  }

无法弄清楚如何在 GestureDetector 中实现 SVG,它无法进入,因为 Image 和 Gesture Detector 不接受图标,或者我做得不对。

感谢

标签: flutterdartsvggesturedetector

解决方案


如果要更改onTap方法上的图像,iconButton则必须使用更改in方法的路径imageonTapsetState

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";
                });
},
            ),
      ),
    );
  }

编辑:(对于手势检测器,您可以简单地将 SVG 包裹在其中)

the iconbutton 替换为 the GestureDetector并添加它的onTapandonTapUp方法。

  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,
    ),
  ),

有关 GestureDetector 和 Flutter SVG 的更多信息,请单击此处


推荐阅读