因項目中的訂單頁需要一個定時器,比如下單後需要進行倒計時,等倒計時完後,訂單狀態自動關閉。
如圖:
這裏顯示等17分25秒就是我們所需要做的功能。
項目裏還有其他倒計時類型,比如年月日,天之類的,
先上一個工具類:
//時間格式化,根據總秒數轉換爲對應的 hh:mm:ss 格式
static String constructTime(int seconds) {
int day = seconds ~/3600 ~/24;
int hour = seconds ~/ 3600;
int minute = seconds % 3600 ~/ 60;
int second = seconds % 60;
if(day != 0){
return '$day天$hour小時$minute分$second秒後自動取消';
}else if(hour != 0){
return '$hour小時$minute分$second秒後自動取消';
}else if(minute !=0){
return '$minute分$second秒後自動取消';
}else if(second!=0){
return '$second秒後自動取消';
}else {
return '';
}
// return formatTime(day)+'天'+formatTime(hour) + "小時" + formatTime(minute) + "分" + formatTime(second)+'秒後自動取消';
}
static String constructVipTime(int seconds) {
int day = seconds ~/3600 ~/ 24;
int hour = seconds ~/ 3600;
int minute = seconds % 3600 ~/ 60;
int second = seconds % 60;
if(day!= 0){
return '剩$day天$hour小時$minute分';
}else if(hour!= 0){
return '剩$hour小時$minute分';
}else if(minute!=0){
return '剩$minute分';
}else {
return '';
}
// return formatTime(day)+'天'+formatTime(hour) + "小時" + formatTime(minute) + "分" + formatTime(second)+'秒後自動取消';
}
//數字格式化,將 0~9 的時間轉換爲 00~09
static String formatTime(int timeNum) {
return timeNum < 10 ? "0" + timeNum.toString() : timeNum.toString();
}
再看一下如何使用:
class OrderPageState extends State<OrderPage> {
String countContent ; // 倒計時內容
Timer _timer;
int seconds = 0;
///.......
@override
Widget build(BuildContext context) {
countContent = Util.constructTime(seconds);
return new Scaffold(
appBar: HeadTitleBar(
text: '訂單詳情',
rightShow: true,
rightIcPath: ImageConstant.icon_talk_black,
callback: (){
RouteUtil.jump2ChatPage(context);
},),
body: _buildRoot());
}
void cancelTimer() {
if (_timer != null) {
_timer.cancel();
_timer = null;
}
}
void startTimer() {
//設置 1 秒回調一次
const period = const Duration(seconds: 1);
_timer = Timer.periodic(period, (timer) {
//更新界面
setState(() {
//秒數減一,因爲一秒回調一次
seconds --;
// print('我在更新界面>>>>>>>>>>>>>> $seconds');
});
if (seconds == 0) {
//倒計時秒數爲0,取消定時器
print('我被取消了 ');
cancelTimer();
getData();
}
});
}
void getData() async{
await DioUtil.request("xxx",
method: DioUtil.GET,
).then((res) {
var time = res.orderExprieTime;
if(time !=null){
try{
var _diffDate = DateTime.parse(time.toString());
//獲取當期時間
var now = DateTime.now();
var twoHours = _diffDate.difference(now);
//獲取總秒數,2 分鐘爲 120 秒
seconds = twoHours.inSeconds;
startTimer();
}catch(e){
seconds = 0;
}
}
}
loading = true;
if(!mounted)return;
setState(() {
});
}).catchError((e){
});
}
@override
void dispose() {
super.dispose();
cancelTimer();
}
}
注意:一定要在dispose方法中銷燬該定時器,不然會一隻走下去的,其中countContent
可以寫在具體的text中,大概就是這樣。
更多文章查看個人主頁: