Flutter onTap method for Containers
Screenshot:
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
:
Both share many features in common like
onTap
,onLongPress
etc. The main difference is thatGestureDetector
has more controls like dragging and so on. On the other hand,InkWell
provides some nice ripple effects.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 withGestureDetector
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), ), )
You could wrap container inside an Inkwell() or in GestureDetector() as below
InkWell(
child: Container(...),
onTap: () {
print("tapped on container");
},
);
Using the Gesture Detector
GestureDetector(
onTap: () { print("Container was tapped"); },
child: Container(...),
)
The only difference between the two is InkWell provides a ripple effect when the pointer is in contact with the screen while this is no such visual feedback with GestureDetector.
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.