Flutter how to change image after onTap with Gesture Detector

≡放荡痞女 提交于 2021-02-10 18:23:24

问题


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.


回答1:


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




回答2:


I haven't tested this myself, so give it a try and see if it suits your need.

For such application, you could give provider a try.

For example,

final provider = Provider.of<myProvider>(context);

...
Image(
   image: AssetImage(provider.imageFile),
),     
...
GestureDetector(
  onTapDown: () => provider.imageForTapDown(),
  onTapUp: () => provider.imageForTapUp()
);

then in provider,

void imageForTapDown(){
 //Change the image file
 imageFile = changeImageforTapDown;

 notifyListeners();
)

void imageForTapUp(){
 //Change the image file
 imageFile = changeImageforTapUp;

 notifyListeners();
)

You can read more about the provider.

Make sure you apply optimization as notifyListeners will rebuild whenever listen: true in the provider (you can target specific image using selector of provider).

Hope this helps.



来源:https://stackoverflow.com/questions/59792716/flutter-how-to-change-image-after-ontap-with-gesture-detector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!