Flutter: How do you make a card clickable?

In the world of Flutter, creating user interfaces is very easy. With its simple syntax, developers can quickly create visually appealing apps that are both responsive and easy to navigate. In this blog post, we’ll dive into how you can make a card in Flutter click-able.

Use Composition Over Properties

In object-oriented programming (OOP), composition over inheritance is a design principle that suggests preferring composition to inheritance whenever possible. This means instead of inheriting the properties and behavior of another class, we create objects from other classes and compose them into our own class.

class ClickableCard extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // code here
  }
}

However, in Flutter, this principle is taken to the next level with something called widget composition. It’s a technique where you create complex UI components by combining simpler widgets together. This approach helps keep your code organized and easier to maintain.

Wrapping Widgets for Clickability

The key to making a card clickable in Flutter is understanding that we need to wrap the desired widget into another widget that provides the click functionality. This concept may be unfamiliar if you’re coming from other programming paradigms, but it’s central to how Flutter works.

// Wrap your Card widget with GestureDetector or InkWell
GestureDetector(
  onTap: () => print('Card clicked'),
  child: Card(...),
);

Some Clickable Widgets in Flutter

In Flutter, there are several widgets that make a part of the screen click-able. The most common ones used for this purpose are GestureDetector, InkWell, and InkResponse.

Gestures Detector

The GestureDetector is one such widget in Flutter which lets you register callback methods for various user gestures like tap, double tap, long press etc., on a portion of the screen. The onTap callback can be used to handle what happens when the user taps on it.

GestureDetector(
  onTap: () => print('Card clicked'),
  child: Card(...),
);

InkWell

Another very useful widget in Flutter is InkWell, which besides letting you register a callback for tap events also displays the Material Design ripple effect when tapped. This effect can help visually indicate to users that their action has been registered and processed.

Card(
  child: InkWell(
    onTap: () {
      print('tapped');
    },
    child: Container(
      width: 100.0,
      height: 100.0,
    ),
  ),
);

Conclusion

In conclusion, making a card clickable in Flutter is all about wrapping the desired widget into another that provides the click functionality. With GestureDetector and InkWell being some of the most commonly used widgets for this purpose, developers can easily add interactive elements to their UIs.