Home > database >  How to add delay to a button in flutter
How to add delay to a button in flutter

Time:08-22

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

CodePudding user response:

You can use Future.delayed to run your code after some time. e.g.:

Future.delayed(const Duration(milliseconds: 500), () {

// Here you can write your code

  setState(() {
    // Here you can write your code for open new view
  });

});

In setState function, you can write a code which is related to app UI e.g. refresh screen data, change label text, etc.

CodePudding user response:

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

CodePudding user response:

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