0

How can I prevent button spamming in flutter I tried

Future delayed

but it still can be spammed I believe I should add this before the onPressed but I couln't do that

3 Answers3

0

You can use something like AbsorbPointer widget with a timer to disable action for a certain amount of time after the action, or you can simply set your onTap method to null in that time without using AbsorbPointer

Fadel
  • 195
  • 1
  • 9
0

You can create a flag which you can set to false once user presses the button one time. Then after certain time the flag will become true again. The button action only will happen if the flag=true.

So create the flag

bool goodToGo = true;

Then onPressed of the button

onPressed:(){
      if(!goodToGo){return;}
      if(goodToGo){debugPrint("Going to the moon!");}// do your thing
      goodToGo = false;
      Future.delayed(const Duration(milliseconds: 3000), () {
          goodToGo = true;
      });
}
0

To add delay to a button's onTap callback and avoid multiple unnecessary gestures (i.e. the user accidentally presses the button quickly two times causing the onTap callback to be invoked twice), you should use a boolean flag (e.g. isTapped). For example:

  @override
  Widget build(BuildContext context) {
    bool isTapped = false;
    return ElevatedButton(
        onPressed: () async {
          if (!isTapped) {
            isTapped = true;
            await Future.delayed(const Duration(milliseconds: 160));
            
            Navigator.of(context).pushNamed('/textvoice');
            
            isTapped = false;
          }
        },
        child: const Text('delayed splash effect')
    );
  }