onLongPress
- Flutter course
- Beginner
- Lesson 53/99
- 4 min
Learn to catch long press with onLongPress.
onLongPress
onLongPress is called when the user holds a finger on the widget for about 500 milliseconds. Unlike a single tap, it requires holding for a certain duration, which makes it suitable for context menus or "more options" actions.
GestureDetector(
onTap: () => print('Single'),
onLongPress: () => print('Long pressed'),
child: Container(width: 80, height: 80),
)The long press duration
GestureDetector has no parameter to set the long press duration; the duration is fixed. Finer control requires lower-level classes, which is beyond this lesson. In most cases the default duration is sufficient and you do not configure it separately.
Practice Catch long press with onLongPress
Write a function longPress that prints Long pressed. In main call longPress and give the GestureDetector an empty function as onTap and longPress as onLongPress.
Starter code
import 'package:flutter/material.dart';
// uzunBasma fonksiyonu "Uzun basildi" yazdirmali
// GestureDetector'a onTap ve onLongPress bagla
void main() {
// uzunBasma'yi 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 ve onLongPress parametrelerini ekle
child: Container(
width: 100,
height: 100,
color: Colors.red,
),
),
),
),
);
}
}Sample solution
import 'package:flutter/material.dart';
void uzunBasma() {
print('Uzun basildi');
}
void main() {
uzunBasma();
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: () {},
onLongPress: uzunBasma,
child: Container(
width: 100,
height: 100,
color: Colors.red,
),
),
),
),
);
}
}Expected output
Uzun basildi
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 When is onLongPress triggered?
- When the finger is held down for a while Correct answer
- On double tap
- As soon as tapped
- On horizontal drag
Explanation: onLongPress requires the finger to remain pressed on the widget for a certain duration (about 500 ms).
2 Add the onLongPress parameter
GestureDetector(
onTap: () => print('Tek'),
____: () => print('Uzun'),
child: Text('B'),
)
GestureDetector(
onTap: () => print('Tek'),
onLongPress: () => print('Uzun'),
child: Text('B'),
)
Explanation: The long press callback is given with the onLongPress parameter; onPress, onHold or onLongClick are not valid.
3 Long press parts
| Term | Meaning |
|---|---|
onLongPress |
Long press callback |
500 ms |
Approximate waiting time |
onTap |
Short tap callback |
child |
The widget whose gestures are captured |