Handle taps

Domains: Flutter

You not only want to display information to users, you want users to interact with your app. Use the GestureDetector widget to respond to fundamental actions, such as tapping and dragging.

This recipe shows how to make a custom button that shows a snackbar when tapped with the following steps:

  1. Create the button.
  2. Wrap it in a GestureDetector that an onTap() callback.
// The GestureDetector wraps the button.
GestureDetector(
  // When the child is tapped, show a snackbar.
  onTap: () {
    final snackBar = SnackBar(content: Text("Tap"));

    Scaffold.of(context).showSnackBar(snackBar);
  },
  // The custom button
  child: Container(
    padding: EdgeInsets.all(12.0),
    decoration: BoxDecoration(
      color: Theme.of(context).buttonColor,
      borderRadius: BorderRadius.circular(8.0),
    ),
    child: Text('My Button'),
  ),
);

Notes

  1. For information on adding the Material ripple effect to your button, see the Add Material touch ripples recipe.
  2. Although this example creates a custom button, Flutter includes a handful of button implementations, such as: RaisedButton, FlatButton, and CupertinoButton.

Similar pages

Page structure
Terms

Flutter

Widget

Container