We not only want to display information to our users, we want our users tointeract with our apps! So how do we respond to fundamental actions such astapping and dragging? We’ll use theGestureDetectorWidget!

Say we want to make a custom button that shows a snackbar when tapped. How wouldwe approach this?

Directions

  • Create the button
  • Wrap it in a GestureDetector with an onTap callback
  1. // Our GestureDetector wraps our button
  2. GestureDetector(
  3. // When the child is tapped, show a snackbar
  4. onTap: () {
  5. final snackBar = SnackBar(content: Text("Tap"));
  6. Scaffold.of(context).showSnackBar(snackBar);
  7. },
  8. // Our Custom Button!
  9. child: Container(
  10. padding: EdgeInsets.all(12.0),
  11. decoration: BoxDecoration(
  12. color: Theme.of(context).buttonColor,
  13. borderRadius: BorderRadius.circular(8.0),
  14. ),
  15. child: Text('My Button'),
  16. ),
  17. );

Notes

Complete example

  1. import 'package:flutter/material.dart';
  2. void main() => runApp(MyApp());
  3. class MyApp extends StatelessWidget {
  4. @override
  5. Widget build(BuildContext context) {
  6. final title = 'Gesture Demo';
  7. return MaterialApp(
  8. title: title,
  9. home: MyHomePage(title: title),
  10. );
  11. }
  12. }
  13. class MyHomePage extends StatelessWidget {
  14. final String title;
  15. MyHomePage({Key key, this.title}) : super(key: key);
  16. @override
  17. Widget build(BuildContext context) {
  18. return Scaffold(
  19. appBar: AppBar(
  20. title: Text(title),
  21. ),
  22. body: Center(child: MyButton()),
  23. );
  24. }
  25. }
  26. class MyButton extends StatelessWidget {
  27. @override
  28. Widget build(BuildContext context) {
  29. // Our GestureDetector wraps our button
  30. return GestureDetector(
  31. // When the child is tapped, show a snackbar
  32. onTap: () {
  33. final snackBar = SnackBar(content: Text("Tap"));
  34. Scaffold.of(context).showSnackBar(snackBar);
  35. },
  36. // Our Custom Button!
  37. child: Container(
  38. padding: EdgeInsets.all(12.0),
  39. decoration: BoxDecoration(
  40. color: Theme.of(context).buttonColor,
  41. borderRadius: BorderRadius.circular(8.0),
  42. ),
  43. child: Text('My Button'),
  44. ),
  45. );
  46. }
  47. }

Handling Taps Demo