我嘗試使用 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
},
),
],
),
],
),
)
);
}
uj5u.com熱心網友回復:
用一個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");
},
)
uj5u.com熱心網友回復:
ononLongPressDown()你可以得到DateTimethen 得到 endDateTime從 on 中減去onLongPressUp()
DateTime startTime;
DateTime endTime;
onLongPressDown: (details) {
startTime = DateTime.now();
},
onLongPressUp: () {
endTime = DateTime.now();
longPressDuration = endTime.difference(startTime);
},
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/425255.html
上一篇:如何在反應中添加多個條件?
下一篇:添加退出按鈕時如何洗掉錯誤?
