Flutter实现倒计时功能,秒数转时分秒,然后倒计时

Flutter实现倒计时功能

发布时间:2023/05/12

本文实例为大家分享了Flutter实现倒计时功能的具体代码,供大家参考,具体内容如下

有一个需求,需要在页面进行显示倒计时,倒计时结束后,做相应的逻辑处理。

实现思路:在Flutter中,Timer.periodic提供了循环功能,查看函数定义:

c 复制代码
factory Timer.periodic(Duration duration, void callback(Timer timer))

第一个参数就是时间间隔,第二个参数就是事件处理回调。

由于后台返回的是秒数,所以需要根据总秒数计算小时,分钟,秒。同时,当不满一个小时时,只显示分钟和秒数,当分钟和秒数只有一个数时(比如1分8秒,显示为01:08)前面加"0"处理。

完整代码:

c 复制代码
import 'package:flutter/material.dart';
import 'dart:async';

class CounterDownPage extends StatefulWidget {
  @override
  _CounterDownPageState createState() => _CounterDownPageState();
}

class _CounterDownPageState extends State<CounterDownPage> {
  // 用来在布局中显示相应的剩余时间
  String remainTimeStr = '';
  Timer _timer;

   //倒计时 
  void startCountDown(int time) {
    // 重新计时的时候要把之前的清除掉
    if (_timer != null) {
      if (_timer.isActive) {
        _timer.cancel();
        _timer = null;
      }
    }

    if (time <= 0) {
      return;
    }

    var countTime = time;
    const repeatPeriod = const Duration(seconds: 1);
    _timer = Timer.periodic(repeatPeriod, (timer) { 
      if (countTime <= 0) {
        timer.cancel();
        timer = null;
        //待付款倒计时结束,可以在这里做相应的操作
        
        return;
      }
      countTime--;

    //外面传进来的单位是秒,所以需要根据总秒数,计算小时,分钟,秒
    int hour = (countTime ~/ 3600) % 24;//如果不止24小时的就不用%24
    int minute = countTime % 3600 ~/60;
    int second = countTime % 60;

    var str = '';
    if (hour > 0) {
      str = str + hour.toString()+':';
    }

    if (minute / 10 < 1) {//当只有个位数时,给前面加"0",实现效果:":01",":02"
      str = str + '0' + minute.toString() + ":";
    } else {
      str = str + minute.toString() + ":";
    }

    if (second / 10 < 1) {
      str = str + '0' + second.toString();
    } else {
      str = str + second.toString();
    }

    setState(() {
      remainTimeStr = str;
    });

    });
  }

 @override
  void initState() {
    super.initState();
    //开始倒计时,这里传入的是秒数
     startCountDown(5000);
  }

@override
  void dispose() {
    super.dispose();
    if (_timer != null) {
      if (_timer.isActive) {
        _timer.cancel();
        _timer = null;
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("倒计时"),
      ),
      body: Center(
        child: Row(
       mainAxisAlignment: MainAxisAlignment.center,
       children: [
         Text("剩余", style: TextStyle(
           fontSize: 18,
           color: Color.fromRGBO(255, 111, 50, 1),
           fontWeight: FontWeight.bold
         ),),
          Text(remainTimeStr.length > 0 ? remainTimeStr: "--", style: TextStyle(
           fontSize: 18,
           color: Color.fromRGBO(255, 111, 50, 1),
           fontWeight: FontWeight.bold
         ),),
       ],
      ),
      ),
    );
  }
}

服务器返回的时间戳87392,现在的时间戳+87392 现在的时间戳,两者的时间戳相差二十多个小时,也就是说87392就是秒数,直接传秒数到上面的startCountDown方法即可。

相关推荐
言乐61 小时前
Python实现语音审核模型
开发语言·python·django·virtualenv·pygame
朝朝辞暮i2 小时前
C++ 第 21 课:struct —— 把一组相关数据打包在一起
开发语言·c++·算法
SHARK_pssm3 小时前
【C++——类和对象(下)】
开发语言·c++·经验分享·笔记
凯哥Java3 小时前
写代码怎么避免逻辑漏洞?
java·开发语言·人工智能·自动化
Ai-_Man3 小时前
您您这可以把Dola的多个会话比如说。左侧的多个会话一次性导出吗?不是单条会话里面的多次会对话。用AI导出鸭,答案是可以的
开发语言·前端·人工智能·小程序
Java后端的Ai之路3 小时前
Python进阶探索23 - Python中的Time与Datetime模块
开发语言·数据库·python·datetime·time
沫璃染墨4 小时前
《从零入门Linux系统篇(五十四):线程篇·七——互斥锁底层原理:从原子交换到线程竞争与锁实现》
linux·运维·服务器·开发语言·c++·驱动开发·系统架构
Java后端的Ai之路4 小时前
Python进阶探索24_应用案例_linux系统的监控
linux·开发语言·python·应用·探索
程序员清风4 小时前
PydanticAI 实战:用类型安全构建可靠的 Python Agent
开发语言·python·安全
落魄实习生4 小时前
Agent Scope Java 2.x 系列【10】Middleware
java·开发语言·ai