每5秒更新小部件
我需要用“ N Now N Now Now On It On It”这样的颤音来做小部件,n来自后端,如果可见小部件,我需要每5秒更新一次。
我尝试了几种方法future.delayed
和Timer
像这样的方法:
_timer = Timer(
const Duration(seconds: 5),
() {
if (isCounterVisible) {
// load data
}
},
);
@override
void dispose() async {
if (_timer != null) {
_timer!.cancel();
_timer = null;
}
}
但是面对我离开此屏幕后仍会发送的问题,并且单位测试失败了的原因,即使在将小部件树处置
之后,计时器仍在等待中
,我在确定小部件是否可见时也有问题。我使用了库visibility_detector
,但似乎它与模态窗口不起作用 - 在显示模态窗口时,侦听器不会触发。
I need to do the widget with Flutter like "N users watch on it now", where N comes from the backend, and I need to update it every 5 seconds if the widget is visible.
I tried a few approaches with Future.delayed
and Timer
like this ones:
_timer = Timer(
const Duration(seconds: 5),
() {
if (isCounterVisible) {
// load data
}
},
);
@override
void dispose() async {
if (_timer != null) {
_timer!.cancel();
_timer = null;
}
}
But facing an issue that requests still sending after I go away from this screen, and unit tests failed for the reason A Timer is still pending even after the widget tree was disposed
Also, I have problems with determining is widget visible or not. I used library visibility_detector
but seems it does not work with modal windows - the listener does not trigger when the modal window showed.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
timer.periodic
将完成这项工作,您也可以使用可取消的未来。您缺少super.dispose();
。现在,使用
inittimer()
启动woker。Timer.periodic
will do the job, Also you can use cancelable future. You are missingsuper.dispose();
.Now use
initTimer()
to start woker.您可以使用RiverPod StreamProvider.Autodispose包裹在计时器周围。当不再引用时,它将自动消失。
You could use a RiverPod StreamProvider.autoDispose wrapped around a Timer.periodic to wake up a Consumer Widget at regular intervals. It will automatically go away when no longer referenced.