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

1,950

Solution 1

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

Solution 2

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)
Share:
1,950
Anitesh Reddy
Author by

Anitesh Reddy

Updated on December 21, 2022

Comments

  • Anitesh Reddy
    Anitesh Reddy over 1 year

    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

  • Hosea varghese
    Hosea varghese over 3 years
    thanks for the dartPad. People are awesome