网站建设有哪些规章制度,网站集约建设报告,公众号平台官网网页版,四大门户网站Flutter实现倒计时功能 发布时间#xff1a;2023/05/12 本文实例为大家分享了Flutter实现倒计时功能的具体代码#xff0c;供大家参考#xff0c;具体内容如下
有一个需求#xff0c;需要在页面进行显示倒计时#xff0c;倒计时结束后#xff0c;做相应的逻辑处理。
实…Flutter实现倒计时功能 发布时间2023/05/12 本文实例为大家分享了Flutter实现倒计时功能的具体代码供大家参考具体内容如下
有一个需求需要在页面进行显示倒计时倒计时结束后做相应的逻辑处理。
实现思路在Flutter中Timer.periodic提供了循环功能查看函数定义
factory Timer.periodic(Duration duration, void callback(Timer timer))第一个参数就是时间间隔第二个参数就是事件处理回调。
由于后台返回的是秒数所以需要根据总秒数计算小时分钟秒。同时当不满一个小时时只显示分钟和秒数当分钟和秒数只有一个数时比如1分8秒显示为01:08前面加“0”处理。
完整代码
import package:flutter/material.dart;
import dart:async;class CounterDownPage extends StatefulWidget {override_CounterDownPageState createState() _CounterDownPageState();
}class _CounterDownPageState extends StateCounterDownPage {// 用来在布局中显示相应的剩余时间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小时的就不用%24int minute countTime % 3600 ~/60;int second countTime % 60;var str ;if (hour 0) {str str hour.toString():;}if (minute / 10 1) {//当只有个位数时给前面加“0”实现效果“:01”,:02str 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;});});}overridevoid initState() {super.initState();//开始倒计时这里传入的是秒数startCountDown(5000);}overridevoid dispose() {super.dispose();if (_timer ! null) {if (_timer.isActive) {_timer.cancel();_timer null;}}}overrideWidget 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方法即可。