如何测量用户按下按钮的时间?
How do I measure how long the user held down a button?
我尝试使用计时器 class,但它仅从固定持续时间 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
},
),
],
),
],
),
)
);
}
在 onLongPressDown()
你可以得到 DateTime
然后得到结束 DateTime
从 onLongPressUp()
减去
DateTime startTime;
DateTime endTime;
onLongPressDown: (details) {
startTime = DateTime.now();
},
onLongPressUp: () {
endTime = DateTime.now();
longPressDuration = endTime.difference(startTime);
},
使用 Stopwatch
在 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");
},
)
我尝试使用计时器 class,但它仅从固定持续时间 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
},
),
],
),
],
),
)
);
}
在 onLongPressDown()
你可以得到 DateTime
然后得到结束 DateTime
从 onLongPressUp()
DateTime startTime;
DateTime endTime;
onLongPressDown: (details) {
startTime = DateTime.now();
},
onLongPressUp: () {
endTime = DateTime.now();
longPressDuration = endTime.difference(startTime);
},
使用 Stopwatch
在 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");
},
)