flutter - 如何启用/禁用与倒数计时器相关的用于电话验证的按钮 ("resend code"按钮?

标签 flutter dart flutter-layout

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

最佳答案

您可以使用 Timer 这样做来自 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

关于flutter - 如何启用/禁用与倒数计时器相关的用于电话验证的按钮 ("resend code"按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62952821/

相关文章:

flutter : TextField with FocusNode does not get called when clicked outside of TextField

ios - Flutter 将 com.apple.security.network.client 添加到 *.entitlements

android - 如何启动Firebase模拟器?

flutter - 我的水平滚动遇到麻烦- flutter

listview - flutter 中非动态容器小部件的水平传送带

flutter - 在 Flutter 的 main/App 类中调用方法?

flutter - 带有ListView的Streambuilder在每个图 block 中显示相同的数据?

flutter - Flutter 中带有内嵌图像的文本

flutter - 用于插件开发的 FlutterWeb 的 WebView 支持

flutter - 使用 Flutter 嵌套和同步 ListView (类似调度程序)