Flutter实现倒计时功能

本文深入探讨了Flutter中定时器的使用技巧,包括如何利用Timer进行循环查询和倒计时功能的实现,通过代码示例详细解析了不同刷新频率对视觉效果的影响。

题记
—— 执剑天涯,从你的点滴积累开始,所及之处,必精益求精,即是折腾每一天。

**你可能需要
CSDN网易云课堂教程
掘金EDU学院教程
知乎Flutter系列文章

本文是异步编程的定时器策略篇章,通过Timer来实现。
定时器的使用场景一般如下

  • 间隔一定的时间循环发起查询
  • 倒计时

通过Timer实现间隔一定时间的循环执行

Timer的periodic函数开启一个循环执行的任务,其参数一用来配制间隔执行这个任务的时间,参数二用来配置具体执行的任务,在使用时需要注意有创建就要有销毁,以避免内存泄漏,如开启一个间隔1秒的定时任务,如下代码清单1-1所示:

class _FutureLoopTestPageState extends State {
  ///声明变量
  Timer _timer;

  @override
  void initState() {
    super.initState();

    ///循环执行
    ///间隔1秒
    _timer = Timer.periodic(Duration(milliseconds: 1000), (timer) {
      ///定时任务
    });
  }

  @override
  void dispose() {
    ///取消计时器
    _timer.cancel();
    super.dispose();
  }
  ...
}
实现一个APP启动页面的倒计时

如下图所示为常见App的一个启动页面的倒计时显示效果,对应代码清单 1-3.
在这里插入图片描述
对应的实现代码如下:

///代码清单 1-3 实现一个倒计时
class FutureLoopTestPage2 extends StatefulWidget {
  @override
  _FutureLoopTestPageState createState() => _FutureLoopTestPageState();
}

//lib/code/main_data.dart
class _FutureLoopTestPageState extends State<FutureLoopTestPage2> {
  ///声明变量
  Timer _timer;
  ///记录当前的时间
  int curentTimer = 0;

  @override
  void initState() {
    super.initState();

    ///循环执行
    ///间隔1秒
    _timer = Timer.periodic(Duration(milliseconds: 1000), (timer) {
      ///自增
      curentTimer++;
      ///到5秒后停止 
      if (curentTimer == 5) {
        _timer.cancel();
      }
      setState(() {});
    });
  }

  @override
  void dispose() {
    ///取消计时器
    _timer.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("倒计时"),
      ),
      backgroundColor: Colors.white,

      ///填充布局
      body: Container(
          padding: EdgeInsets.all(20),
          width: double.infinity,
          height: double.infinity,
          child: Column(
            children: [
              ///层叠布局将进度与文字叠在一起
              Stack(
                ///子Widget居中
                alignment: Alignment.center,
                children: [
                  ///圆形进度
                  CircularProgressIndicator(
                    ///当前指示的进度 0.0 -1.0
                    value: curentTimer / 5,
                  ),
                  ///显示的文本
                  Text("${5-curentTimer}"),
                ],
              )
            ],
          )),
    );
  }
}

在上述代码清单 1-3 中所示的效果,圆形进度执行的有点死板的效果,如下图所示为优化后的效果,给人的视觉效果比较舒适,对应代码清单1-4。
在这里插入图片描述

///代码清单 1-4 
class FutureLoopTestPage3 extends StatefulWidget {
  @override
  _FutureLoopTestPageState createState() => _FutureLoopTestPageState();
}

//lib/code/main_data.dart
class _FutureLoopTestPageState extends State<FutureLoopTestPage3> {
  ///声明变量
  Timer _timer;
  ///记录当前的时间
  int curentTimer = 0;

  @override
  void initState() {
    super.initState();

    ///循环执行
    ///间隔1秒
    _timer = Timer.periodic(Duration(milliseconds: 100), (timer) {
      ///自增
      curentTimer+=100;
      ///到5秒后停止
      if (curentTimer >= 5000) {
        _timer.cancel();
      }
      setState(() {});
    });
  }

  @override
  void dispose() {
    ///取消计时器
    _timer.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("倒计时"),
      ),
      backgroundColor: Colors.white,

      ///填充布局
      body: Container(
          padding: EdgeInsets.all(20),
          width: double.infinity,
          height: double.infinity,
          child: Column(
            children: [
              ///层叠布局将进度与文字叠在一起
              Stack(
                ///子Widget居中
                alignment: Alignment.center,
                children: [
                  ///圆形进度
                  CircularProgressIndicator(
                    ///当前指示的进度 0.0 -1.0
                    value: curentTimer / 5000,
                  ),
                  ///显示的文本
                  Text("${(curentTimer/1000).toInt()}"),
                ],
              )
            ],
          )),
    );
  }
}

代码清单 1-3 与代码 清单1-4中所示的效果有完全不同的视觉效果,在代码实现的方式上只是刷新频率的不一样。


完毕
公众号 我的大前端生涯

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

早起的年轻人

创作源于分享

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值