timer在實際的項目開發中用的不是很多,但是對于一些訂單的頁面還是會用的到,網上關于timer的資料不是很多,對于一些復雜的使用場景沒有提到.此文根據在實際項目中的使用整理了一個demo.再此開源,純屬技術交流,歡迎評論交流.
先展示一下最終的實現效果
最終實現效果
實現思路:
實現思路就是界面里面使用一個定時器,然后在倒計時里對數據源里面的時間字段就行減一操作,再刷新界面就可以了,思路很簡單.但是定時器廢了勁了.
遇到問題:
下拉刷新定時器加速問題
問題代碼:
class TimerPage extends StatefulWidget {
const TimerPage({Key? key}) : super(key: key);
@override
State<TimerPage> createState() => _TimerPageState();
}
class _TimerPageState extends State<TimerPage> {
late Timer _timer;
List dataList = [
500,
620,
700,
820,
960,
180,
200,
220,
];
late EasyRefreshController _controller;
@override
void initState() {
// TODO: implement initState
super.initState();
_controller = EasyRefreshController(
);
creatData();
}
void creatData() {
var date = DateTime.parse("2022-11-10 21:20:41");
var today = DateTime.now();
var difference = date.difference(today);
int timeCount = difference.inSeconds;
dataList.insert(0, timeCount);
startTimer();
}
void startTimer() {
// _timer.cancel();
// _timer = null;
List list = dataList;
_timer = Timer.periodic(const Duration(seconds: 1), (Timer timer) {
for (int i = 0; i < list.length; i++) {
var tempTime = list[i];
if (tempTime == 0) {
} else {
tempTime -= 1;
}
list[i] = tempTime;
}
print('哈哈哈哈哈哈哈');
setState(() {
dataList = list;
});
});
}
@override
Widget build(BuildContext context) {
/// 寫一個下拉刷新的列表 定時器加速問題
return Scaffold(
appBar: AppBar(
title: const Text('定時器使用'),
),
body: EasyRefresh(
controller: _controller,
firstRefresh: false,
header: ClassicalHeader(),
footer: ClassicalFooter(),
onRefresh: () async {
await Future.delayed(const Duration(seconds: 1));
creatData();
_controller.resetLoadState();
},
child: ListView.builder(
shrinkWrap: true,
physics: const AlwaysScrollableScrollPhysics(),
itemCount: dataList.length,
itemBuilder: (BuildContext context, int index) {
return Container(
height: 50,
alignment: Alignment.center,
margin: const EdgeInsets.only(left: 15, right: 15, top: 15),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(6),
boxShadow: const [
BoxShadow(
color: Colors.black12,
offset: Offset(0.0, 0.0), //陰影xy軸偏移量
blurRadius: 2.0, //陰影模糊程度
spreadRadius: 2.0 //陰影擴散程度
)
]),
child: Text(
FormatUtils.constructTime(dataList[index]),
style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w500),
),
);
}),
)
);
}
@override
void dispose() {
// TODO: implement dispose
super.dispose();
_timer.cancel();
// _timer = null;
_controller.dispose();
}
}
用late關鍵字
顯式聲明一個非空的變量,但不初始化。
如果不加late
關鍵字,類實例化時此值是不確定的,無法通過靜態檢查,加上late
關鍵字可以通過靜態檢查,但由此會帶來運行時風險。但是我在下拉刷新的時候timer
又重新創建了一個,所以就出現了定時器的加速的問題.我在定時器里面打印了內容,發現下拉刷新一次之后,打印的內容是兩個兩個打印的,在退出當前頁面以后還有一個定時器在打印.
所以,一開始我就在startTimer
方法里添加了_timer.cancel()
這行代碼,發現timer
停止了,一個都不走了.我當時思考給timer
加一個final
,修改代碼如下'_timer@484517720' has already been initialized.
就可以解決這個問題,結果下拉刷新時報錯了_timer@484517720' has already been initialized.
提示timer
對象已經存在了,不能重復創建.是因為final
表示單分配
,最終變量或字段必須具有初始化程序。一旦分配了值
,最終變量的值
就無法更改。
最后又經過了一番嘗試,終于解決了這個問題,先上代碼.
class TimerPage extends StatefulWidget {
const TimerPage({Key? key}) : super(key: key);
@override
State<TimerPage> createState() => _TimerPageState();
}
class _TimerPageState extends State<TimerPage> {
Timer? _timer;
List dataList = [
500,
620,
700,
820,
960,
180,
200,
220,
];
late EasyRefreshController _controller;
@override
void initState() {
// TODO: implement initState
super.initState();
_controller = EasyRefreshController(
);
}
void creatData() {
var date = DateTime.parse("2022-11-10 21:20:41");
var today = DateTime.now();
var difference = date.difference(today);
int timeCount = difference.inSeconds;
dataList.insert(0, timeCount);
startTimer();
}
void startTimer() {
_timer?.cancel();
_timer = null;
List list = dataList;
_timer = Timer.periodic(const Duration(seconds: 1), (Timer timer) {
for (int i = 0; i < list.length; i++) {
var tempTime = list[i];
if (tempTime == 0) {
} else {
tempTime -= 1;
}
list[i] = tempTime;
}
print('哈哈哈哈哈哈哈');
setState(() {
dataList = list;
});
});
}
@override
Widget build(BuildContext context) {
/// 寫一個下拉刷新的列表 定時器加速問題
return Scaffold(
appBar: AppBar(
title: const Text('定時器使用'),
),
body: EasyRefresh(
controller: _controller,
firstRefresh: true,
header: ClassicalHeader(),
footer: ClassicalFooter(),
onRefresh: () async {
await Future.delayed(const Duration(seconds: 1));
creatData();
_controller.resetLoadState();
},
child: ListView.builder(
shrinkWrap: true,
physics: const AlwaysScrollableScrollPhysics(),
itemCount: dataList.length,
itemBuilder: (BuildContext context, int index) {
return Container(
height: 50,
alignment: Alignment.center,
margin: const EdgeInsets.only(left: 15, right: 15, top: 15),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(6),
boxShadow: const [
BoxShadow(
color: Colors.black12,
offset: Offset(0.0, 0.0), //陰影xy軸偏移量
blurRadius: 2.0, //陰影模糊程度
spreadRadius: 2.0 //陰影擴散程度
)
]),
child: Text(
FormatUtils.constructTime(dataList[index]),
style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w500),
),
);
}),
)
);
}
@override
void dispose() {
// TODO: implement dispose
super.dispose();
_timer?.cancel();
_timer = null;
_controller.dispose();
}
}
其實就是聲明timer
時,這樣聲明Timer? _timer;
在startTimer
中將上一個timer
取消,并置為null
,再重新創建一個timer
,就解決了這個問題.
注意點
一定要記住在dispose
中加上下面的代碼,不然的話定時器是不會釋放,容易引起內存的問題.
@override
void dispose() {
// TODO: implement dispose
super.dispose();
_timer?.cancel();
_timer = null;
_controller.dispose();
}
到此我們就可以很愉快的使用定時器了,純屬技術交流,不喜勿噴,歡迎評論交流.