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; if (tempTime == 0) { } else { tempTime -= 1; } list = 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; if (tempTime == 0) { } else { tempTime -= 1; } list = 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(); }到此我们就可以很舒畅的利用定时器了,纯属技术互换,不喜勿喷,接待品评互换.
demo地址请移步: 项目地址
Flutter TabBar 在实际项目中的运用: 项目地址 |