Flutter onTap method for Containers

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 widget which is not a button ?

Here is a code sample :

  child: new Container(

    //INSERT ONTAP OR ONPRESSED METHOD HERE

    margin: const EdgeInsets.symmetric(vertical: 10.0),
    child: new Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        new Container(
          margin: const EdgeInsets.only(right: 16.0),
          child: new GoogleUserCircleAvatar(snapshot.value['images'][0]),
        ),
        new Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children : [
            new Container(
              padding: const EdgeInsets.only(bottom: 8.0),
              child: new Text("${snapshot.value['name']}",
                style: new TextStyle(
                  fontWeight: FontWeight.bold,
                ),
              ),
             ),
            new Text("${snapshot.value['description']}",
              style: new TextStyle(
                color: Colors.grey[500],
              ),
            ),
          ]
        )
      ],
    ),

Solution 1:

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.

Solution 2:

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

Solution 3:

Screenshot:

enter image description here


You can use both GestureDetector and InkWell but I'll suggest you to go for InkWell as it can show ripple effects which a GestureDetector can't.

Differences between GestureDetector and InkWell:

  1. Both share many features in common like onTap, onLongPress etc. The main difference is that GestureDetector has more controls like dragging and so on. On the other hand, InkWell provides some nice ripple effects.

  2. You can use either of them according to your needs. If you want ripple effect choose InkWell, and if you need more controls then go with GestureDetector or even combine both of them.

    Material(
      color: Colors.blue, // Background color
      child: InkWell(
        splashColor: Colors.grey, // Splash color
        onTap: () => print("Container pressed"), // Handle your onTap here.
        child: Container(height: 200, width: 200),
      ),
    )