首页 > 解决方案 > 如何启用/禁用与倒数计时器相关的按钮(用于电话验证的“重新发送代码”按钮)?

问题描述

我有一个按钮,它应该会在 30 秒内出现。倒计时从 30 秒开始。当它达到 0 时,应该出现/启用重新发送代码按钮。

在此处输入图像描述

标签: flutterdartflutter-layout

解决方案


你可以这样做使用Timerfrom dart:async..

class MyWidget extends StatefulWidget {
  @override
  _MyWidgetState createState() => _MyWidgetState();
}

class _MyWidgetState extends State<MyWidget> {
  int secondsRemaining = 30;
  bool enableResend = false;
  Timer timer;

  @override
  initState() {
    super.initState();
    timer = Timer.periodic(Duration(seconds: 1), (_) {
      if (secondsRemaining != 0) {
        setState(() {
          secondsRemaining--;
        });
      } else {
        setState(() {
          enableResend = true;
        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        TextField(),
        const SizedBox(height: 10),
        FlatButton(
          child: Text('Submit'),
          color: Colors.blue,
          onPressed: () {
            //submission code here
          },
        ),
        const SizedBox(height: 30),
        FlatButton(
          child: Text('Resend Code'),
          onPressed: enableResend ? _resendCode : null,
        ),
        Text(
          'after $secondsRemaining seconds',
          style: TextStyle(color: Colors.white, fontSize: 10),
        ),
      ],
    );
  }
  
  void _resendCode() {
    //other code here
    setState((){
      secondsRemaining = 30;
      enableResend = false;
    });
  }
  
  @override
  dispose(){
    timer.cancel();
    super.dispose();
  }
  
}

链接到 Dartpad 上的代码 - https://dartpad.dev/a59c751c4f6b4721a7af1cc27c67650b


推荐阅读