前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Flutter 快速上手定时器/倒计时及实战讲解

Flutter 快速上手定时器/倒计时及实战讲解

作者头像
AndroidTraveler
发布2019-06-15 21:32:03
2.1K0
发布2019-06-15 21:32:03
举报
文章被收录于专栏:AndroidTravelerAndroidTraveler

本文微信公众号「AndroidTraveler」首发。

今天给大家讲讲 Flutter 里面定时器/倒计时的实现。

一般有两种场景:

  1. 我只需要你在指定时间结束后回调告诉我。回调只需要一次。
  2. 我需要你在指定时间结束后回调告诉我。回调可能多次。

下面针对这两种场景,我们来说下如何在 Flutter 里面使用。

回调一次的定时器
代码语言:javascript
复制
const timeout = const Duration(seconds: 5);print('currentTime='+DateTime.now().toString());Timer(timeout, () {  //到时回调  print('afterTimer='+DateTime.now().toString());});

这里我们设置了超时时间为 5 秒。然后启动一个定时器,等到 5 秒时候到了,就会执行回调方法。

我们在定时器启动之前和之后都加上了打印日志,控制台打印输出如下:

代码语言:javascript
复制
flutter: currentTime=2019-06-08 13:56:35.347493flutter: afterTimer=2019-06-08 13:56:40.350412

用法总结起来就是:

1.设置超时时间 timeout 2.启动定时器 Timer(timeout, callback) 3.处理回调 callback

回调多次的定时器

回调多次的定时器用法和回调一次的差不多,区别有下面两点:

  1. API 调用不同
  2. 需要手动取消,否则会一直回调,因为是周期性的

一样的我们通过一个简单的小例子来说明:

代码语言:javascript
复制
int count = 0;const period = const Duration(seconds: 1);print('currentTime='+DateTime.now().toString());Timer.periodic(period, (timer) {  //到时回调  print('afterTimer='+DateTime.now().toString());  count++;  if (count >= 5) {    //取消定时器,避免无限回调    timer.cancel();    timer = null;  }});

这里我们的功能是每秒回调一次,当达到 5 秒后取消定时器,一共 回调了 5 次。

控制台输出如下

代码语言:javascript
复制
flutter: currentTime=2019-06-08 14:16:02.906858flutter: afterTimer=2019-06-08 14:16:03.909963flutter: afterTimer=2019-06-08 14:16:04.910538flutter: afterTimer=2019-06-08 14:16:05.911942flutter: afterTimer=2019-06-08 14:16:06.911741flutter: afterTimer=2019-06-08 14:16:07.910227

用法总结起来就是:

1.设置周期回调时间 period 2.启动定时器 Timer.periodic(period, callback(timer)) 3.处理回调 callback(timer) 4.记得在合适时机取消定时器,否则会一直回调

好了,有了上面的知识储备,接下来,让我们进入实战讲解环节。

实战讲解
业务场景

服务器返回一个时间,你根据服务器的时间和当前时间的对比,显示倒计时,倒计时的时间在一天之内,超过一天显示默认文案即可。

场景分析

这个业务场景在倒计时这一块就需要使用到我们上面的知识了。由于限定了倒计时是在一天之内,所以显示的文案就是从 00:00:00 到 23:59:59。

具体代码操作

基本思路:首先我们需要获得剩余时间,接着启动一个 1 秒的周期性定时器,然后每隔一秒更新一下文案。

直接上代码:

代码语言:javascript
复制
//时间格式化,根据总秒数转换为对应的 hh:mm:ss 格式String constructTime(int seconds) {  int hour = seconds ~/ 3600;  int minute = seconds % 3600 ~/ 60;  int second = seconds % 60;  return formatTime(hour) + ":" + formatTime(minute) + ":" + formatTime(second);}

//数字格式化,将 0~9 的时间转换为 00~09String formatTime(int timeNum) {  return timeNum < 10 ? "0" + timeNum.toString() : timeNum.toString();}

//获取当期时间var now = DateTime.now();//获取 2 分钟的时间间隔var twoHours = now.add(Duration(minutes: 2)).difference(now);//获取总秒数,2 分钟为 120 秒var seconds = twoHours.inSeconds;//设置 1 秒回调一次const period = const Duration(seconds: 1);//打印一开始的时间格式,为 00:02:00print(constructTime(seconds));Timer.periodic(period, (timer) {  //秒数减一,因为一秒回调一次  seconds--;  //打印减一后的时间  print(constructTime(seconds));  if (seconds == 0) {    //倒计时秒数为0,取消定时器    timer.cancel();    timer = null;  }});

其实注释也写的很清楚了,就是基本思路的基础上增加了一些细节处理,这里演示是自己构造了一个两分钟的倒计时。

好了,基本到这里已经说完了,但是可能 Flutter 具体一些细节还不一样,这边直接给下一个倒计时的完整代码吧。

代码语言:javascript
复制
import 'dart:async';import 'package:flutter/material.dart';
class Countdown extends StatefulWidget {  @override  _CountdownState createState() => _CountdownState();}
class _CountdownState extends State<Countdown> {
  Timer _timer;  int seconds;
  @override  Widget build(BuildContext context) {    return Center(      child: Text(constructTime(seconds)),    );  }
  //时间格式化,根据总秒数转换为对应的 hh:mm:ss 格式  String constructTime(int seconds) {    int hour = seconds ~/ 3600;    int minute = seconds % 3600 ~/ 60;    int second = seconds % 60;    return formatTime(hour) + ":" + formatTime(minute) + ":" + formatTime(second);  }
  //数字格式化,将 0~9 的时间转换为 00~09  String formatTime(int timeNum) {    return timeNum < 10 ? "0" + timeNum.toString() : timeNum.toString();  }
  @override  void initState() {    super.initState();    //获取当期时间    var now = DateTime.now();    //获取 2 分钟的时间间隔    var twoHours = now.add(Duration(minutes: 2)).difference(now);    //获取总秒数,2 分钟为 120 秒    seconds = twoHours.inSeconds;    startTimer();  }
  void startTimer() {    //设置 1 秒回调一次    const period = const Duration(seconds: 1);    _timer = Timer.periodic(period, (timer) {      //更新界面      setState(() {        //秒数减一,因为一秒回调一次        seconds--;      });      if (seconds == 0) {        //倒计时秒数为0,取消定时器        cancelTimer();      }    });  }
  void cancelTimer() {    if (_timer != null) {      _timer.cancel();      _timer = null;    }  }
  @override  void dispose() {    super.dispose();    cancelTimer();  }
}

效果如下:

后续打算写一个 FlutterApp 涵盖我之前博客的例子,方便大家结合代码查看实际运行效果,敬请期待。

这边之前创建了一个知识星球,欢迎互联网小伙伴加入,一起学习,共同成长。 链接方式加入: 我正在「Flutter(限免)」和朋友们讨论有趣的话题,你一起来吧? https://t.zsxq.com/MVrJiAY

扫码方式加入:

右下角

也是一种支持

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-06-10,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 安卓小煜 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 回调一次的定时器
  • 回调多次的定时器
  • 实战讲解
    • 业务场景
      • 场景分析
        • 具体代码操作
        • 右下角
        • 也是一种支持
        领券
        问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档