【问题标题】:How can I create a sub-timer in flutter?如何在颤振中创建子计时器?
【发布时间】:2021-05-01 21:48:30
【问题描述】:

我的 Flutter 应用中有一个周期性计时器,它每 x 秒更改一次页面上的一些值:

periodicTimer = new Timer.periodic(Duration(seconds: timer), (Timer t) {
            setState(() {
              if (globals.selectedBottomNav == 0) {
                nextKey();
              } else {
                nextCircleKey();
              }
            });
          });

但是,我需要能够在更短的时间内执行另一项操作。因此,例如,如果我的 timer 变量设置为 5 秒,我需要能够每 5 秒运行一次 setState,但在每个定时循环的 3 秒后,我想运行一些其他代码。

对我如何实现这一目标有任何帮助吗?我尝试了各种嵌套的 Timer 和 Timer.periodic 选项,但得到了奇怪的结果。

谢谢

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    如果您打算使用单个计时器完成此操作,那么缩短该计时器的持续时间并自己计算秒数怎么样

    int secondsCounter = 0;
    periodicTimer = new Timer.periodic(Duration(seconds: 1), (Timer t) {
      secondsCounter++;
      
      if(secondsCounter == 3){
        // do stuff that's supposed to happen after 3 seconds
      } else if(secondsCounter == 5){
        // do stuff that's supposed to happen after 5 seconds
      }
      
      if(secondsCounter >= 5){
        secondsCounter = 0;
      }
    });
    

    【讨论】:

    • 谢谢,这正是我想要的
    【解决方案2】:

    我认为这个简单的实现没有任何问题。如果您对此有意外行为,请更新您的问题,详细解释预期与实际行为,以及您尝试过的任何其他解决方案。

    periodicTimer = new Timer.periodic(Duration(seconds: timer), (Timer t) {
      Timer(Duration(seconds: 3), () {
        // perform other operations here
      });
    
      setState(() {
        if (globals.selectedBottomNav == 0) {
          nextKey();
        } else {
          nextCircleKey();
        }
      });
    });
    

    【讨论】:

    • 感谢您的回复。我确实尝试了类似的方法,但是在我停止进程后执行第二个计时器时得到了奇怪的结果。很可能是我的编码:-) Alex 的解决方案解决了我的问题。
    猜你喜欢
    • 2018-07-21
    • 2021-02-25
    • 2021-05-10
    • 2020-02-18
    • 2021-10-12
    • 2021-07-07
    • 2021-09-17
    • 1970-01-01
    • 2021-02-13
    相关资源
    最近更新 更多