Handle taps
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:
- Create the button.
- Wrap it in a
GestureDetector
that anonTap()
callback.
dart
// The GestureDetector wraps the button.
GestureDetector(
// When the child is tapped, show a snackbar.
onTap: () {
const snackBar = SnackBar(content: Text('Tap'));
ScaffoldMessenger.of(context).showSnackBar(snackBar);
},
// The custom button
child: Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: Colors.lightBlue,
borderRadius: BorderRadius.circular(8),
),
child: const Text('My Button'),
),
)
Notes
#- For information on adding the Material ripple effect to your button, see the Add Material touch ripples recipe.
- Although this example creates a custom button, Flutter includes a handful of button implementations, such as:
ElevatedButton
,TextButton
, andCupertinoButton
.
Interactive example
#import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
const title = 'Gesture Demo';
return const MaterialApp(
title: title,
home: MyHomePage(title: title),
);
}
}
class MyHomePage extends StatelessWidget {
final String title;
const MyHomePage({super.key, required this.title});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(title),
),
body: const Center(
child: MyButton(),
),
);
}
}
class MyButton extends StatelessWidget {
const MyButton({super.key});
@override
Widget build(BuildContext context) {
// The GestureDetector wraps the button.
return GestureDetector(
// When the child is tapped, show a snackbar.
onTap: () {
const snackBar = SnackBar(content: Text('Tap'));
ScaffoldMessenger.of(context).showSnackBar(snackBar);
},
// The custom button
child: Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: Colors.lightBlue,
borderRadius: BorderRadius.circular(8),
),
child: const Text('My Button'),
),
);
}
}
Unless stated otherwise, the documentation on this site reflects the latest stable version of Flutter. Page last updated on 2024-07-06. View source or report an issue.