乐闻世界logo
搜索文章和话题

How do you make a card clickable in Flutter?

1个答案

1

In Flutter, to make a Card clickable, the common approach is to wrap the Card with GestureDetector or InkWell. Both handle user touch events, but InkWell provides a ripple effect compared to GestureDetector, which typically offers better user feedback.

Here is an example using InkWell:

dart
import 'package:flutter/material.dart'; void main() { runApp(MaterialApp( home: Scaffold( body: Center( child: MyClickableCard(), ), ), )); } class MyClickableCard extends StatelessWidget { Widget build(BuildContext context) { return InkWell( onTap: () { // This executes the action after tapping print('Card tapped!'); }, child: Card( elevation: 5, child: Container( width: 300, height: 100, padding: EdgeInsets.all(20), child: Text('Click Me', style: TextStyle(fontSize: 20)), ), ), ); } }

In this example, we create a custom StatelessWidget named MyClickableCard. InkWell wraps the Card and handles tap events via the onTap property. When the card is tapped, it outputs 'Card tapped!' to the console. This way, users not only see the ripple effect but also experience actual functionality (in this case, printing a message).

Using GestureDetector is similar, but it lacks the ripple effect and can handle additional gestures like double taps or long presses.

This approach is widely applicable in real-world development scenarios, such as product lists, news cards, or any situation requiring clickable elements.

2024年8月8日 01:15 回复

你的答案