每 x 秒执行一次颤振运行功能 [英] flutter run function every x amount of seconds

查看:33
本文介绍了每 x 秒执行一次颤振运行功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 flutter 应用程序中,我想每 10 秒检查一次我的 api.我发现 这篇文章 每隔 x 运行一个函数时间量并执行以下操作:

inside my flutter app I want to check my api every 10 seconds. I found this post to run a function every x amount of time and did the following:

class _MainPage extends State<MainPage> {
  int starter = 0;

  void checkForNewSharedLists(){
    // do request here
    setState((){
      // change state according to result of request
    });

  }

  Widget build(BuildContext context) {
    Timer.periodic(Duration(seconds: 15), (Timer t) => checkForNewSharedLists());
  }
} 

不幸的是,请求堆积如山:在第一轮重新启动应用程序后,api 有两个请求,第二轮是四个请求,第三轮是八个请求,依此类推...

Unfortunately the requests pile up: after restarting the app on the first "round" there are two request to the api, the second round it's four requests, the third it's eight and so on...

有人知道如何解决这个问题吗?

Does anybody know how to fix this?

推荐答案

build() 可以并且通常会被多次调用,并且每次都会调用一个新的 Timer.periodic 已创建.

build() can and usually will be called more than once and every time a new Timer.periodic is created.

您需要将该代码从 build() 中移出,例如

You need to move that code out of build() like

Timer? timer;

@override
void initState() {
  super.initState();
  timer = Timer.periodic(Duration(seconds: 15), (Timer t) => checkForNewSharedLists());
}

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

更好的做法是将这些代码从 API 层或类似层中的小部件中完全移出,并使用 StreamBuilder 在数据更新时更新视图.

Even better would be to move out such code from widgets entirely in an API layer or similar and use a StreamBuilder to have the view updated in case of updated data.

这篇关于每 x 秒执行一次颤振运行功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆