Ad

How Do I Measure How Long The User Held Down A Button?

- 1 answer

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
Ad