Flutter實(shí)現(xiàn)倒計時功能
發(fā)布時間:2023/05/12
本文實(shí)例為大家分享了Flutter實(shí)現(xiàn)倒計時功能的具體代碼,供大家參考,具體內(nèi)容如下
有一個需求,需要在頁面進(jìn)行顯示倒計時,倒計時結(jié)束后,做相應(yīng)的邏輯處理。
實(shí)現(xiàn)思路:在Flutter中,Timer.periodic提供了循環(huán)功能,查看函數(shù)定義:
factory Timer.periodic(Duration duration, void callback(Timer timer))
第一個參數(shù)就是時間間隔,第二個參數(shù)就是事件處理回調(diào)。
由于后臺返回的是秒數(shù),所以需要根據(jù)總秒數(shù)計算小時,分鐘,秒。同時,當(dāng)不滿一個小時時,只顯示分鐘和秒數(shù),當(dāng)分鐘和秒數(shù)只有一個數(shù)時(比如1分8秒,顯示為01:08)前面加“0”處理。
完整代碼:文章來源:http://www.zghlxwxcb.cn/news/detail-641729.html
import 'package:flutter/material.dart';
import 'dart:async';
class CounterDownPage extends StatefulWidget {
@override
_CounterDownPageState createState() => _CounterDownPageState();
}
class _CounterDownPageState extends State<CounterDownPage> {
// 用來在布局中顯示相應(yīng)的剩余時間
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;
//待付款倒計時結(jié)束,可以在這里做相應(yīng)的操作
return;
}
countTime--;
//外面?zhèn)鬟M(jìn)來的單位是秒,所以需要根據(jù)總秒數(shù),計算小時,分鐘,秒
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) {//當(dāng)只有個位數(shù)時,給前面加“0”,實(shí)現(xiàn)效果:“: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();
//開始倒計時,這里傳入的是秒數(shù)
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
),),
],
),
),
);
}
}
服務(wù)器返回的時間戳87392,現(xiàn)在的時間戳+87392 現(xiàn)在的時間戳,兩者的時間戳相差二十多個小時,也就是說87392就是秒數(shù),直接傳秒數(shù)到上面的startCountDown方法即可。文章來源地址http://www.zghlxwxcb.cn/news/detail-641729.html
到了這里,關(guān)于Flutter實(shí)現(xiàn)倒計時功能,秒數(shù)轉(zhuǎn)時分秒,然后倒計時的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!