Search code examples
flutterdartflutter-image

Flutter how to change image after onTap with Gesture Detector


I have a Image inside a GestureDetector widget. I want to change this image when onTapDown is called, and then change it again when onTapUp is called. Is there possible to do that? In other app (Native Android app with java), I used to do it using a button and changing its background with a selector xml, like this:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="true" android:state_pressed="false" android:drawable="@drawable/image1" />
<item android:state_focused="true" android:state_pressed="true" android:drawable="@drawable/image2" />
<item android:state_focused="false" android:state_pressed="true" android:drawable="@drawable/image2"/>
<item android:drawable="@drawable/image1" />

so, is there a way to do the same in flutter?

---JUST TO BE CLEAR---

In the same widget, I want an image if it is not pressed and a different image if it is pressed.


Solution

  • Image img;
    // example: Image.asset('images/camera.png',)
    Image imgUp =  Image.asset('your image directory for when tap up',);
    Image imgDown =  Image.asset('your image directory for when tapdown',);
    
     @override
     void initState() {
     super.initState();
     img = imgUp;
     }
    
    
    GestureDetector(
          //your image is here
          child: img,
          onTapDown: (tap){
            setState(() {
              // when it is pressed
              img =  imgDown;
            });
          },
          onTapUp: (tap){
            setState(() {
              // when it is released
              img = imgUp;
            });
          }, 
    

    full code You can change the image when it is pressed and released using gesture detector It is super easy you don't need any extra library or package you have to just use setState() in order to update the view when you pressed an released