想要在用户点击按钮后禁用按钮 30 秒,然后在 flutter 中自动启用它

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

我在一个登录系统上工作,我通过 OTP 验证用户,在这里我想禁用 Resend OTP 按钮 30 秒,每次用户点击它并显示剩余时间

用 true 声明布尔值 onPressedValue 变量, 在onPressed参数中添加条件

bool onPressedValue=true;

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

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

}:null)

你可以试试这个

Declare a variable call like this globally

bool shouldButtonEnabled=true;

然后在单击发送 OTP 按钮时调用此方法,而您发送 OTP 等其他东西在它之后调用此方法

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

并且在像这样重新发送 OTP 按钮时选中此布尔值

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

如果您想要一个实时计数器来向用户显示过去的秒数,您应该使用流生成器

            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,
                )
                );
              },
            )

你可以在 dartpad.dev 上找到完整的代码 link