Summary - GestureDetector
- Flutter course
- Beginner
- Lesson 55/99
- 4 min
Combine GestureDetector callbacks to make a tappable card.
Combine callbacks
A single GestureDetector can take onTap, onDoubleTap, onLongPress and onHorizontalDragUpdate callbacks together. You only need to provide the ones you need; not all are required. Flutter detects the gesture that occurred and calls the right callback.
GestureDetector(
onTap: () => print('Single'),
onLongPress: () => print('Long'),
onHorizontalDragUpdate: (d) => print(d.delta.dx),
child: Container(width: 100, height: 100),
)Practice Combine three callbacks in one GestureDetector
Write the functions singleTap, doubleTap and longPress that print Single, Double and Long respectively. In main call singleTap and wire all three callbacks to the GestureDetector.
Starter code
import 'package:flutter/material.dart';
// tekDokunus "Tek" yazdirsin
// ciftDokunus "Cift" yazdirsin
// uzunBasma "Uzun" yazdirsin
// hepsini GestureDetector'a bagla
void main() {
// tekDokunus'u cagir
runApp(const Uygulama());
}
class Uygulama extends StatelessWidget {
const Uygulama({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: GestureDetector(
// onTap, onDoubleTap, onLongPress ekle
child: Container(
width: 120,
height: 120,
color: Colors.orange,
),
),
),
),
);
}
}Sample solution
import 'package:flutter/material.dart';
void tekDokunus() {
print('Tek');
}
void ciftDokunus() {
print('Cift');
}
void uzunBasma() {
print('Uzun');
}
void main() {
tekDokunus();
runApp(const Uygulama());
}
class Uygulama extends StatelessWidget {
const Uygulama({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: GestureDetector(
onTap: tekDokunus,
onDoubleTap: ciftDokunus,
onLongPress: uzunBasma,
child: Container(
width: 120,
height: 120,
color: Colors.orange,
),
),
),
),
);
}
}Expected output
Tek
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which callbacks must be provided in a GestureDetector?
- Only the ones needed; none are mandatory Correct answer
- All of them are mandatory
- Only onTap is mandatory
- onTap and onLongPress must be provided together
Explanation: All callback parameters of GestureDetector are optional; you provide only the callbacks for the gestures you want to capture.
2 Complete onDoubleTap
GestureDetector(
onTap: () => print('a'),
onLongPress: () => print('b'),
____: () => print('c'),
child: Text('X'),
)
GestureDetector(
onTap: () => print('a'),
onLongPress: () => print('b'),
onDoubleTap: () => print('c'),
child: Text('X'),
)
Explanation: Three callbacks can be used together; the correct parameter name for double tap is onDoubleTap.
3 GestureDetector callbacks
| Term | Meaning |
|---|---|
onTap |
Single tap |
onDoubleTap |
Double tap |
onLongPress |
Long press |
onHorizontalDragUpdate |
Horizontal drag |