每5秒更新小部件

发布于 2025-02-13 02:57:29 字数 678 浏览 0 评论 0原文

我需要用“ N Now N Now Now On It On It”这样的颤音来做小部件,n来自后端,如果可见小部件,我需要每5秒更新一次。

我尝试了几种方法future.delayedTimer像这样的方法:

            _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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

梦罢 2025-02-20 02:57:29

timer.periodic将完​​成这项工作,您也可以使用可取消的未来。您缺少super.dispose();

Timer? timer;

void initTimer() {
  if (timer != null && timer!.isActive) return;

  timer = Timer.periodic(const Duration(seconds: 5), (timer) {
    //job
    setState(() {});
  });
}

@override
void dispose() {
  timer?.cancel();
  super.dispose();
}

现在,使用inittimer()启动woker。

Timer.periodic will do the job, Also you can use cancelable future. You are missing super.dispose();.

Timer? timer;

void initTimer() {
  if (timer != null && timer!.isActive) return;

  timer = Timer.periodic(const Duration(seconds: 5), (timer) {
    //job
    setState(() {});
  });
}

@override
void dispose() {
  timer?.cancel();
  super.dispose();
}

Now use initTimer() to start woker.

标点 2025-02-20 02:57:29

您可以使用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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文