Flutter onTap method for Containers

后端 未结 5 913
粉色の甜心
粉色の甜心 2021-02-03 17:56

Been developing a flutter app and dynamicly building some containers from some Firebase data. I wanted to know if there is a way to get a onTap method for containers (or any wi

相关标签:
5条回答
  • 2021-02-03 18:25

    Difference

    InkWell is a material widget and it can show you a Ripple Effect whenever a touch was received.

    GestureDetector is more general-purpose, not only for touch but also for other gestures.

    In Flutter, InkWell is a material widget that responds to touch action.

    InkWell(
        child: Container(......),
        onTap: () { 
            print("Click event on Container"); 
        },
    );
    

    GestureDetector is a widget that detects the gestures.

    GestureDetector(
        onTap: () { 
            print("Click event on Container"); 
        },
        child: Container(.......),
    )
    
    0 讨论(0)
  • 2021-02-03 18:28

    wrapping the container inside an Inkwell() Widget could solve the problem or even GestureDetector() as

      InkWell(                        
            child: Container(...),                        
            onTap: () {                          
            print("tapped on container");
            },                      
         );
    

    Using the Gesture Detector

    GestureDetector(
      onTap: () { print("Container was tapped"); },
      child: Container(...),
    )
    
    0 讨论(0)
  • 2021-02-03 18:29

    You can wrap your Container in an InkWell or GestureDetector. The difference is that InkWell is a material widget that shows a visual indication that the touch was received, whereas GestureDetector is a more general purpose widget that shows no visual indicator.

    0 讨论(0)
  • 2021-02-03 18:30

    Screenshot:


    You shouldn't use GestureDetector because it won't show you any ripple effect (which is core part of a Material design app), so you can use InkWell, here is the basic example.

    Widget _buildContainer() {
      return Material(
        color: Colors.blue,
        child: InkWell(
          onTap: () => print("Container pressed"), // handle your onTap here
          child: Container(height: 200, width: 200),
        ),
      );
    }
    
    0 讨论(0)
  • 2021-02-03 18:33

    Apart from what others have said in answers, if you use Card inside InkWell, then InkWell will hide away the ripply effect on Android—you can see it happening in the background but not on the card itself.

    Solution to that is to create an InkWell inside the Card.

    return Card(
      child: InkWell(
        child: Row(
          // Row content
        ),
        onTap: () => {
          print("Card tapped.");
        },
      ),
      elevation: 2,
    );
    

    This will help you gain the ripple effect and perform the tap captures on Android too.

    0 讨论(0)
提交回复
热议问题