Flutter: How can I limit the number of times a user can click on a button in a given time period?

Viewed 891

I'm using a button that displays a prompt in a snackbar. Right now if I press the button rapidly, say 50 times, the snackbar appears for a few seconds, then again, and then again, till it's shown 50 times. How can I prevent this?

Here's my code-

          actions: <Widget>[
            Padding(
              padding: const EdgeInsets.all(8.0),
              child: RaisedButton(
                elevation: 7,
                color: Colors.black26,
                child: Text('Button'),
                onPressed: () {
                  _scaffoldKey.currentState
                      .showSnackBar(SnackBar(content: Text("Welcome")));
                },
              ),
            ),
          ],

2 Answers

You can use tap_debouncer package to get rid of your problem. Just use cooldown feature to disable the button press for a limited period time so to prevent multiple taps. There are also many other features provided by the package which can be used to solve your problem.

There are different ways to solve this problem. One is, you can easily prevent multiple taps for a while.

           bool _enabled = true;


           onPressed: !_enabled
            ? null 
            : () {
              setState(() => _enabled = false);
              _scaffoldKey.currentState
                  .showSnackBar(SnackBar(content: Text("Welcome")));
             
               // Enable it after 1s.
               Timer(Duration(seconds: 1), () => setState(() => _enabled = true));
            },
Related