【问题标题】:Flutter how to change image after onTap with Gesture Detector颤振如何使用手势检测器在 onTap 后更改图像
【发布时间】:2020-05-04 15:47:39
【问题描述】:

我在 GestureDetector 小部件中有一个图像。我想在调用 onTapDown 时更改此图像,然后在调用 onTapUp 时再次更改它。有可能这样做吗? 在其他应用程序(带有 java 的本机 Android 应用程序)中,我曾经使用按钮并使用选择器 xml 更改其背景,如下所示:

<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" />

那么,有没有办法在颤振中做同样的事情?

---只是为了清楚---

在同一个小部件中,如果它没有被按下,我想要一个图像,如果它被按下,我想要一个不同的图像。

【问题讨论】:

    标签: flutter dart flutter-image


    【解决方案1】:

    我自己没有测试过,所以试试看它是否适合你的需要。

    对于这样的应用,你可以试试provider

    例如,

    final provider = Provider.of<myProvider>(context);
    
    ...
    Image(
       image: AssetImage(provider.imageFile),
    ),     
    ...
    GestureDetector(
      onTapDown: () => provider.imageForTapDown(),
      onTapUp: () => provider.imageForTapUp()
    );
    

    然后在provider

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

    您可以阅读有关provider 的更多信息。

    确保您应用优化,因为notifyListeners 将在提供程序中的listen: true 时重建(您可以使用提供程序的selector 定位特定图像)。

    希望这会有所帮助。

    【讨论】:

      【解决方案2】:
      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 您可以使用手势检测器在按下和释放时更改图像 超级简单,您不需要任何额外的库或包,您只需使用 setState() 以便在您按下释放时更新视图

      【讨论】:

        猜你喜欢
        • 2019-02-07
        • 1970-01-01
        • 1970-01-01
        • 2023-04-11
        • 1970-01-01
        • 2021-11-21
        • 2021-12-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多