【发布时间】: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 错误
问题
如何停止计时器?
【问题讨论】: