Search code examples
flutterbuttondelayfuture

How do we wait for the user to finish tapping a button until the user made up his/her decision (in flutter)?


For instance we have a like button that when the user press it, it will call an http function somewhere in the cloud.

FlatButton(
  onPressed: () => callOnLikeFunction(),
);

What if the user pressed it multiple times (like and unlike over and over)? Then it will call the http function many times and can cause errors.

So I tried using

Future.delayed(Duration(seconds: 2)).then(() => 
callOnLikeFunction()
);

But this does not work because it will still fire as many times as pressed, just delayed.

So the question is how do we wait until the last press as the final decision of the user and ignore the other attempts?

Update: Defining the last tap: Suppose a user taps 3x with 500ms interval but the 3rd tap stands the test of time of 2seconds then the 3rd tap is considered the last tap


Solution

  • You can use a boolean flag to decide what to do after the button press. After the first tap, the boolean switches and displays f.e. a Snackbar to indicate that the request is in progress.

    requestIsInAction = false;
    
    void buttonCallback() {
      if(!requestIsInAction) {
        requestIsInAction = true;
        // do the http stuff
      }
      else {
        // show error
      }
    }
    

    After the request finishes, set the flag to false again.

    If you want to get the LAST tap, you can use a Timer, as it is suggested at that post. Basically, you decide for the amount of time that has to pass until the button press actually gets proccessed and set the timer for that duration. Each consequent button press can then reset the timer.

    I would use the first solution though because the expected behaviour of a button is that it gets executed immediatly.