英文:
Restart timer after button is clicked
问题
我有一个问题。我有几个按钮。我希望如果用户点击一个按钮,标签应该显示10秒。现在我有以下问题。正如我所说,我有几个按钮。
如果用户点击button1
,则应该将isTagActive == True
设置为10秒。
这对我有用。
但问题是,如果用户点击button1
,然后2秒后点击button2
,isTagActive == True
也只显示10秒。但是计时器应该在button2
设置后重新开始。因此,计时器从第一个按钮开始计数,但应该从最后一个点击的按钮开始计数。我该如何更改这个?
所以,如果用户点击按钮,计时器应该从头开始。
代码:
void processClick() async {
setState(() {
number++;
});
changeActiveStatus();
...
}
// 这是方法
Future<void> changeActiveStatus() async {
isTagActive = true;
if(mounted) {
setState(() {});
}
await Future.delayed(const Duration(seconds: 10), () {
isTagActive = false;
if(mounted) {
setState(() {});
}
});
}
英文:
I have a problem. I have several buttons. I want if the user clicks one button a label should be shown 10 seconds. Now I have the follwing problem. As I said I have several buttons.
If the user clicks button1
the isTagActive == True
should be set for 10 seconds.
This works for me.
But the problem is, if the user clicks button1
and after 2 seconds button2
the isTagActive == True
is also shown only 10 seconds. But it the timer should start from new after button2
is set. So the the timer counts from the first button, but the should counts from the last button is clicked. How could I change this?
So if the user clicks a button the timer should start from beginning.
Code
void processClick() async {
setState(() {
number++;
});
changeActiveStatus();
...
}
// This is the method
Future<void> changeActiveStatus() async {
isTagActive = true;
if(mounted) {
setState(() {});
}
await Future.delayed(const Duration(seconds: 10), () {
isTagActive = false;
if(mounted) {
setState(() {});
}
});
}
答案1
得分: 1
如果您的意图是重置时间,您可以使用防抖。
void processClick() async {
setState(() {
number++;
});
changeActiveStatus();
...
}
Timer? _debounce;
// 这是方法
Future<void> changeActiveStatus() async {
isTagActive = true;
if (mounted) {
setState(() {});
}
if (_debounce?.isActive ?? false) _debounce!.cancel();
_debounce = Timer(
const Duration(seconds: 10),
() {
isTagActive = false;
if (mounted) {
setState(() {});
}
},
);
}
英文:
If your intent is to reset the time, you could use debounce.
void processClick() async {
setState(() {
number++;
});
changeActiveStatus();
...
}
Timer? _debounce;
// This is the method
Future<void> changeActiveStatus() async {
isTagActive = true;
if (mounted) {
setState(() {});
}
if (_debounce?.isActive ?? false) _debounce!.cancel();
_debounce = Timer(
const Duration(seconds: 10),
() {
isTagActive = false;
if (mounted) {
setState(() {});
}
},
);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论