Home > other >  Flutter - How to delay a function for some seconds
Flutter - How to delay a function for some seconds

Time:04-04

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?

CodePudding user response:

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;
  }
}

CodePudding user response:

You can use Future.delay or Timer() class to achieve that.

CodePudding user response:

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));
}

CodePudding user response:

I don't think that your goal is to delay the function. You're trying to find a way to let the user wait until the ErrorSnackbar is gone, right?

Try this approach. It saves the time when a button was clicked the last time and cancels every button press until 2 seconds have passed.

DateTime lastPressed = DateTime(0);

  tappedButton(int index) async {
    DateTime now = DateTime.now();
    if (lastPressed.difference(now).inSeconds < 2) {
      // button pressed again in under 2 seconds, cancel action
      return;
    }
    lastPressed = now;
    final userAnswer = await userAnswer();
    if (userAnswer) {
      // answer correct
    } else{
      // answer incorrect
      ErrorSnackbar();
    }
  }
  • Related