Want to disable the button for 30 second after the user clicks on it and then enable it automatically in flutter

Viewed 2408

I am working on a login system, where i authenticate user by OTP ,Here i want to disable the Resend OTP button for 30 seconds every time the user clicks it and show the time remaining

3 Answers

if you want to have a live counter for showing the user the seconds past you should use stream builder

            StreamBuilder(
              stream: _timerStream.stream,
              builder: (BuildContext ctx,
                  AsyncSnapshot snapshot) {
                return SizedBox(
                  width: 300,
                  height: 30,
                  child:RaisedButton(
                  textColor: Theme.of(context)
                      .accentColor,
                  child: Center(
                      child:
                      snapshot.data == 0 ?
                      Text('send code again')
                          : Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: <Widget>[
                          Text(' button will be enable after ${snapshot.hasData ? snapshot.data.toString() : 30} seconds '),
                        ],)
                  ),
                  onPressed: snapshot.data == 0 ? () {
                    // your sending code method

                    _timerStream.sink.add(30);
                    activeCounter();
                  } : null,
                )
                );
              },
            )

you can find complete code on dartpad.dev with this link

Declare boolean onPressedValue variable with true, Add Condition in onPressed Parameter.

bool onPressedValue=true;

RaisedButton(
  child: Text('OTP'),
  onPressed: onPressedValue==true?(){
  setState((){
  onPressedValue=false;

  });
    Timer(Duration(seconds: 30),(){
      setState((){
        onPressedValue=true;
      });
    });

}:null)

You can try this

Declare a variable call like this globally

bool shouldButtonEnabled=true;

then on click of send OTP button call this method while you other stuff like sending OTP call this method after it

  _disabledButton(){
    shouldButtonEnabled=false;
    Timer(
        Duration(seconds: 30),
            () => shouldButtonEnabled=true);
  }

and when check this bool on resend OTP button like this

 onPressed: () {
            if(shouldButtonEnabled){
              //do your work here
            }
    }
Related