Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter - How to delay a function for some seconds

Tags:

flutter

dart

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?

like image 947
Febin Johnson Avatar asked Feb 17 '26 03:02

Febin Johnson


1 Answers

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;
  }
}
like image 158
Marcin Wróblewski Avatar answered Feb 19 '26 04:02

Marcin Wróblewski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!