Flutter – Container onPressed?

In Flutter, you might be wondering how to handle an onPress event on a Container. The reason you can’t use the direct onPressed property like in native Android development is that the Container widget itself does not have this functionality. However, there are alternative solutions.

Solution 1: Using GestureDetector

You can wrap your Container with a GestureDetector and then handle the tap event inside it like so:

new GestureDetector(
    onTap: (){
      print("Container clicked");
    },
    child: new Container(
      width: 500.0,
      padding: new EdgeInsets.fromLTRB(20.0, 40.0, 20.0, 40.0),
      color: Colors.green,
      child: new Column(
          children: [
            new Text("Ableitungen"),
          ]
      ),
    )
)

This will print “Container clicked” in the console whenever you tap on the container.

Problem with GestureDetector

However, using a GestureDetector does not show the ripple effect that Flutter provides. It’s actually designed for more complex gestures, and its usage should be considered when other widgets don’t fit your needs.

Solution 2: Using InkWell

The recommended way in Flutter to handle an onPress event on a widget that doesn’t support it directly is to use InkWell. It’s the most suitable for such purposes and provides the ripple effect, making user experience more native-like.

InkWell(
  onTap: () {}, // Handle your callback
  child: Ink(height: 100, width: 100, color: Colors.blue),
)

Output:

As you can see, InkWell is the perfect substitute for directly using onPressed on a widget that doesn’t support it. The Ink widget wraps your child and creates an area where tapping will trigger the callback provided in onTap. This way, you can easily achieve onPress-like functionality without needing to manually handle gestures.

Remember that Flutter’s widgets are designed with ease of use and a unified UI style as priorities. Sometimes using alternative solutions like these might require slightly more thought, but they’re often the best practice in achieving native-looking results.

Conclusion

In conclusion, if you need to handle an onPress event on a widget that doesn’t support it directly, such as Container, use InkWell. It provides the ripple effect and is designed specifically for this purpose. Don’t forget that sometimes using Flutter’s recommended widgets can make your development process easier and more native-looking.