【问题标题】:How do I measure how long the user held down a button?如何测量用户按住按钮的时间?
【发布时间】:2022-02-07 08:44:07
【问题描述】:

我尝试使用 Timer 类,但这只从固定持续时间 AFAIK 开始倒计时。我有一个按钮,用户可以单击它或长按并按住它 X 秒,最多 10 秒。我已经弄清楚了单击代码,但是如果用户按住按钮,我想记录他按住按钮的时间并执行其他操作。

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
                    },
                  ),
                ],
              ),
            ],
          ),
        )
    );
  }

【问题讨论】:

    标签: flutter dart button time


    【解决方案1】:

    使用Stopwatch

    在类中创建一个实例: 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");
        },
    )
    

    【讨论】:

      【解决方案2】:

      onLongPressDown() 上,您可以得到DateTime,然后在onLongPressUp() 上得到结尾DateTime 以减去

      DateTime startTime;
      DateTime endTime;
      onLongPressDown: (details) {  
          startTime = DateTime.now();
        },
      onLongPressUp: () {
          endTime = DateTime.now();  
          longPressDuration = endTime.difference(startTime);
        },
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-07-27
        • 2012-10-10
        • 2015-06-25
        • 1970-01-01
        • 2010-09-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多