Code前端首页关于Code前端联系我们

Flutter开发实践:定时器/倒计时的实现

terry 2年前 (2023-09-23) 阅读数 77 #移动小程序

Flutter中定时器/倒计时的实现。

一般有两种情况:

  1. 我只是想让你在规定的时间后回电告诉我。回调只需要执行一次。
  2. 我希望您在指定时间后回电告诉我。可能有多个回调请求。

针对这两种场景,我们来讨论一下如何在Flutter中使用它们。

单次回调定时器

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

这里我们将超时设置为5秒。然后启动一个计时器,5秒过去后回调方法将被执行。

我们在计时器启动之前和之后添加了打印日志。控制台打印如下:

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

用法总结如下:

1。设置超时超时 2. 启动计时器 计时器(超时、回调) 3. 处理回调请求 回调

多个回调计时器

使用多个回调计时器与回铃一次的计时器类似。区别如下:

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

我们用一个简单的例子来说明:

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秒就取消定时器,一共回调五次。

控制台输出如下:

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

用法总结为:

1。设置回调周期的周期 2. 启动定时器 Timer.periodic(period, callback(timer)) 3. 处理回调callback(timer) 4. 不要忘记在正确的时间取消定时器,否则会一直保留回电

好了,有了上面的知识储备,我们就开始实战讲解环节吧。

实用讲解

业务场景

服务器返回时间,您根据服务器时间与当前时间的比较显示倒计时。倒计时时间为一天之内。如果花费的时间超过一天,则会显示默认副本。

场景分析

这个业务场景需要在倒计时的时候用到我们上面的知识。由于倒计时仅限于一天内,因此显示的副本是从 00:00:00 到 23:59:59。

具体代码编辑

基本思路:首先我们需要获取剩余时间,然后启动一个1秒的周期性定时器,然后每秒更新副本。

直接上代码:

//时间格式化,根据总秒数转换为对应的 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();
}

//获取当期时间
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:00
print(constructTime(seconds));
Timer.periodic(period, (timer) {
  //秒数减一,因为一秒回调一次
  seconds--;
  //打印减一后的时间
  print(constructTime(seconds));
  if (seconds == 0) {
    //倒计时秒数为0,取消定时器
    timer.cancel();
    timer = null;
  }
});
复制代码

其实注释也很清楚了,在基本思路的基础上又添加了一些细节。这里的演示是自己创建一个两分钟的倒计时。

好了,讲到这里就差不多了,但是 Flutter 的一些具体细节可能会有所不同。让我们给出下一个倒计时的完整代码。

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();
  }

}
复制代码

效果如下: Flutter 开发实战:定时器/倒计时的实现

作者:AndroidTraveler
链接:https://juejin.im/post/5cfdb7666fb9a07ed36e9de4
来源:掘金
版权归作者所有。商业转载请联系作者获得许可。非商业转载请注明出处。

版权声明

本文仅代表作者观点,不代表Code前端网立场。
本文系作者Code前端网发表,如需转载,请注明页面地址。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门