每x秒钟颤动运行功能 [英] flutter run function every x amount of seconds
问题描述
在我的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()
像
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屋!