【问题标题】:Timer does not stop定时器不停止
【发布时间】:2021-10-22 07:53:41
【问题描述】:

问题

我正在聊天。如果没有消息,我希望程序每 5 秒再次尝试获取消息。

我的解决方案

我在有状态的小部件中创建了一个计时器。

Timer timer;

当我构建一个小部件时,我会检查消息。如果没有,我启动计时器。如果有现有消息,我希望计时器在下一次检查时停止

void onBuild() {
    if (state.messages.isEmpty) {
      _checkEmptyMessages();
      timer = Timer.periodic(
          Duration(seconds: 5), (Timer t) => _checkEmptyMessages());
    }
}



void _checkEmptyMessages() {
    print('MES789 ${state.messages.isEmpty}');
    if (state.messages.isEmpty) {
      add(ChatEventLoadFirstPage()); // This adds an event to the BLoC
    } else {
      if (timer != null) timer.cancel();
      timer = null;
    }
  }

我也试过了

我尝试删除 timer = null;await for timer.cancel();,但没有帮助。

实际输出

所以在调试控制台中,我每 5 秒得到一次:

I/flutter (13387):MES789 错误

I/flutter (13387):MES789 错误

I/flutter (13387):MES789 错误

I/flutter (13387):MES789 错误

问题

如何停止计时器?

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    因为调用了“Timer.periodic”,所以创建了新的 Timer 实例并存储了相同的计时器变量。

    这意味着调用'Timer.periodic'时,未取消的计时器实例将丢失。

    所以你需要检查 Timer 实例是否存在。

    void onBuild() {
      if (state.messages.isEmpty) {
          if (timer == null) {
              timer = Timer.periodic(
                  Duration(seconds: 5), (Timer t) => add(ChatEventLoadFirstPage()));
          }
       }  else {
          if (timer != null) timer.cancel();
          timer = null;
        }
    
    }
    

    【讨论】:

      【解决方案2】:

      这个代码是死代码,它永远不会起作用,因为你在_checkEmptyMessages()if (state.messages.isEmpty)之前有if (state.messages.isEmpty),再次尝试删除if (state.messages.isEmpty)

      【讨论】:

      • 逻辑肯定不完美,但是_checkEmptyMessages()不依赖第一个“if”,所以这不是问题,但是第一个“if”可以有“else”分支取消计时器。
      • 视情况而定,上面的答案正好解决了这个问题,还有我的答案
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-09
      • 1970-01-01
      • 2014-09-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多