'Flutter - How to delay a function for some seconds
I have a function which returns false when the user select incorrect answer.
tappedbutton(int index) async {
final userAnswer = await userAnswer();
if (userAnswer) {
// Executing some code
}else{
ErrorSnackbar(); // This snackbar takes 2 second to close.
}
My objective is to delay calling the function for two seconds(user can click the button again , with no action triggering) after the user selects the wrong answer and to prevent the click immediatly. How can i achieve it?
Solution 1:[1]
You'll have to add an helper variable in the outer scope, that will indicate whether the user is on an answer cooldown or not.
The shortest solution will be:
var answerCooldownInProgress = false;
tappedbutton(int index) async {
// Ignore user taps when cooldown is ongoing
if (answerCooldownInProgress) {
return;
}
final userAnswer = await userAnswer();
if (userAnswer) {
// ...
} else {
ErrorSnackbar();
answerCooldownInProgress = true;
await Future.delayed(const Duration(seconds: 2));
answerCooldownInProgress = false;
}
}
Solution 2:[2]
You can use Future.delay or Timer() class to achieve that.
Solution 3:[3]
In order to delay a function you can do below code or use Timer() class
tappedbutton(int index) async {
await Future.delayed(Duration(seconds: 2));
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Marcin Wróblewski |
| Solution 2 | Shashoug |
| Solution 3 | Ahmad Raza |
