【问题标题】:Want to disable the button for 30 second after the user clicks on it and then enable it automatically in flutter想要在用户单击按钮后禁用该按钮 30 秒,然后在颤振中自动启用它
【发布时间】:2020-09-23 16:09:45
【问题描述】:

我正在开发一个登录系统,我通过 OTP 对用户进行身份验证,在这里我想在用户每次单击时禁用 重新发送 OTP 按钮 30 秒并显示剩余时间

【问题讨论】:

标签: android flutter authentication flutter-web one-time-password


【解决方案1】:

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

            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

【讨论】:

  • 感谢 dartPad。人真棒
【解决方案2】:

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

bool onPressedValue=true;

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

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

}:null)

【讨论】:

    【解决方案3】:

    你可以试试这个

    全局声明这样的变量调用

    bool shouldButtonEnabled=true;
    

    然后在点击发送 OTP 按钮时调用此方法,而您在发送 OTP 等其他内容之后调用此方法

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

    当在重新发送 OTP 按钮时检查这个布尔值时

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

    【讨论】:

      猜你喜欢
      • 2020-11-08
      • 1970-01-01
      • 2022-01-08
      • 1970-01-01
      • 2021-09-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-11
      相关资源
      最近更新 更多