一个基于Flutter的倒计时计时器应用程序

class CountdownScreen extends StatefulWidget {
  @override
  _CountdownScreenState createState() => _CountdownScreenState();
}

class _CountdownScreenState extends State<CountdownScreen> {
  int _remainingSeconds = 0; // 剩余时间(秒)
  Timer? _timer; // 定时器
  bool _isRunning = false; // 计时器运行状态
  int _selectedTimeValue = 0; // 选择的时间值(秒)
  late DateTime _currentTime; // 当前时间
  int secondsConversion = 0; // 秒转换值

  TextEditingController textEditingController = TextEditingController();

  @override
  void initState() {
    super.initState();
    _currentTime = DateTime.now();
    _startClock();
  }

  // 递归方式实现实时显示当前时间
  void _startClock() {
    Future.delayed(Duration(seconds: 1), () {
      setState(() {
        _currentTime = DateTime.now();
      });
      _startClock();
    });
  }

  // 弹出选择时间的对话框
  Future<void> _showTimeValueDialog() async {
    int? selectedTimeInSeconds = await showDialog<int>(
      context: context,
      builder: (BuildContext context) {
        int hours = 0;
        int minutes = 0;
        int seconds = 0;

        return AlertDialog(
          title: Text('选择时间值'),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              TextField(
                controller: textEditingController,
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: [
                  SizedBox(
                    width: 50,
                    child: TextField(
                      keyboardType: TextInputType.number,
                      onChanged: (value) {
                        hours = int.tryParse(value) ?? 0;
                      },
                    ),
                  ),
                  Text("时"),
                  SizedBox(
                    width: 50,
                    child: TextField(
                      keyboardType: TextInputType.number,
                      onChanged: (value) {
                        minutes = int.tryParse(value) ?? 0;
                      },
                    ),
                  ),
                  Text("分"),
                  SizedBox(
                    width: 50,
                    child: TextField(
                      keyboardType: TextInputType.number,
                      onChanged: (value) {
                        seconds = int.tryParse(value) ?? 0;
                      },
                    ),
                  ),
                  Text("秒")
                ],
              ),
              ElevatedButton(
                onPressed: () {
                  Navigator.pop(
                    context,
                    hours * 3600 + minutes * 60 + seconds,
                  );
                },
                child: Text('开始'),
              ),
            ],
          ),
        );
      },
    );

    if (selectedTimeInSeconds != null) {
      setState(() {
        _selectedTimeValue = selectedTimeInSeconds;
        _remainingSeconds = selectedTimeInSeconds;
      });
    }
  }

  // 开始计时器
  void startTimer() {
    if (_timer != null) {
      _timer!.cancel();
    }
    _timer = Timer.periodic(Duration(seconds: 1), (timer) {
      setState(() {
        if (_remainingSeconds > 0) {
          _remainingSeconds--;
        } else {
          _timer!.cancel();
          _isRunning = false;
        }
      });
    });
  }

  // 开始/暂停计时器
  void toggleTimer() {
    if (_isRunning) {
      _timer!.cancel();
    } else {
      startTimer();
    }
    setState(() {
      _isRunning = !_isRunning;
    });
  }

  // 停止计时器
  void stopTimer() {
    _timer!.cancel();
    setState(() {
      _remainingSeconds = 0;
      _isRunning = false;
    });
  }

  @override
  void dispose() {
    _timer!.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Text(
            '倒计时: ${_remainingSeconds ~/ 3600}时${(_remainingSeconds % 3600) ~/ 60}分${_remainingSeconds % 60}秒',
            style: TextStyle(fontSize: 24),
          ),
          Text(textEditingController.text),
          SizedBox(height: 20),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              ElevatedButton(
                onPressed: toggleTimer,
                child: Text(_isRunning ? '暂停' : '开始'),
              ),
              SizedBox(width: 20),
              ElevatedButton(onPressed: stopTimer, child: Text("清空"))
            ],
          ),
          ElevatedButton(onPressed: _showTimeValueDialog, child: Text("选择时间"))
        ],
      ),
    );
  }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Flutter 中实现验证码倒计时可以通过使用计时器 Timer 来实现。以下是一个简单的示例: 1. 首先定义一个变量 `countdownTime` 表示倒计时的时间,以秒为单位。 ```dart int countdownTime = 60; ``` 2. 然后定义一个变量 `timer` 来控制计时器的执行。 ```dart Timer timer; ``` 3. 在需要开始倒计时的时候,启动计时器,并在计时器中更新倒计时的时间。 ```dart void startCountdown() { timer = Timer.periodic(Duration(seconds: 1), (timer) { setState(() { if (countdownTime < 1) { timer.cancel(); } else { countdownTime -= 1; } }); }); } ``` 4. 在界面中显示倒计时的时间。可以使用 Text 组件来显示,然后在组件的 text 属性中使用字符串插值来显示倒计时的时间。 ```dart Text('倒计时 $countdownTime 秒') ``` 完整的示例代码如下: ```dart import 'dart:async'; import 'package:flutter/material.dart'; class CountdownPage extends StatefulWidget { @override _CountdownPageState createState() => _CountdownPageState(); } class _CountdownPageState extends State<CountdownPage> { int countdownTime = 60; Timer timer; void startCountdown() { timer = Timer.periodic(Duration(seconds: 1), (timer) { setState(() { if (countdownTime < 1) { timer.cancel(); } else { countdownTime -= 1; } }); }); } @override void dispose() { timer?.cancel(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('验证码倒计时'), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text('倒计时 $countdownTime 秒'), SizedBox(height: 16), RaisedButton( child: Text('开始倒计时'), onPressed: startCountdown, ), ], ), ), ); } } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值