Ad
How Do I Measure How Long The User Held Down A Button?
I tried using the Timer class but that only counts down from a fixed duration AFAIK. I have a button where the user can either single tap it or long press and hold it for X amount of seconds, up to a maximum of 10 seconds. I already figured out the single tap code, but if the user presses and holds the button I want to record how long he held it for and also do other stuff.
Timer startRecordingTimer() => Timer(Duration(milliseconds: 10 * 1000), handleTimeout);
void handleTimeout() {
//when startRecordingTimer() reaches 0, do the following
stopRecording();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Align(
alignment: Alignment.bottomLeft,
child: Column(
children: [
Row(
children: [
GestureDetector(
onTap: () async {
startRecording();
},
onLongPressDown: (details) {
startRecordingTimer();
startRecording();
},
onLongPressUp: () {
//Need to measure how long user held down button
//Do other stuff using the aforementioned duration
},
),
],
),
],
),
)
);
}
Ad
Answer
Use a Stopwatch
Create an instance in the class:
Stopwatch stopwatch = Stopwatch();
GestureDetector(
onTap: () async {
startRecording();
},
onLongPressDown: (details) {
startRecordingTimer();
startRecording();
stopwatch.start();
},
onLongPressUp: () {
stopwatch.stop();
var timeElapsedInSeconds = stopwatch.elapsed.inSeconds;
print("Time elapsed: $timeElapsedInSeconds");
},
)
Ad
source: stackoverflow.com
Related Questions
- → How do you create a 12 or 24 mnemonics code for multiple cryptocurrencies (ETH, BTC and so on..)
- → Flutter: input text field don't work properly in a simple example..... where am I wrong?
- → Can I customize the code formatting of Dart code in Atom?
- → Is it possible to develop iOS apps with Flutter on a Linux virtual machine?
- → Display SnackBar in Flutter
- → JSON ObjectMapper in Flutter
- → Material flutter app source code
- → TabBarSelection No such method error
- → How do I set the animation color of a LinearProgressIndicator?
- → Add different routes/screens to Flutter app
- → Is there a way to get the size of an existing widget?
- → How to share a file using flutter
- → Is there an easy way to find particular text built from RichText in a Flutter test?
Ad