我尝试过使用定时器,每5分钟调用一次api。但它正在阻止其他api调用。有人能指引我吗?
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> with
WidgetsBindingObserver {
int _timerCounter = 0;
Timer? _timer;
@override
void initState() {
try {
super.initState();
WidgetsBinding.instance?.addObserver(this);
_timer = new Timer.periodic(
new Duration(milliseconds: 100000), _incrementTimerCounter);
} catch (error, s) {
Functions.recordError(error, s);
}
}
在初始化时,分配了计时器,当应用程序恢复状态时,该时间也再次分配了计时器。
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
if (state == AppLifecycleState.resumed) {
_timer = new Timer.periodic(
new Duration(milliseconds: 100000),
_incrementTimerCounter);
} else if (state == AppLifecycleState.paused) {
_timer!.cancel();
}
}
void _incrementTimerCounter(Timer t) {
if (!mounted) return;
print("_timerCounter is $_timerCounter");
refereshData();
_timerCounter++;
}
Future refereshData() async {
if (!mounted) return;
if (await Utils.checkConnection()) {
var data = Provider.of<ProviderPostData>(context, listen:
false);
await data.postDataCall(context);
}
}
}
@override
Widget build(BuildContext context) {
return Container();
}
}
我已经通过定时器调用了api。每2分钟我在后台调用一次api。它工作得很好,但也阻止了其他api请求。感谢
最简单的解决方案是创建一个递归callApi
函数,如下所示:
void callApi() {
Future.delayed(const Duration(minutes: 5), (){
// call API functionality
callApi();
});
}
不过有点晦涩。
如果我是你,我会选择可以安排的Firebase功能。不幸的是,它需要Firebase Blaze计划https://firebase.google.com/docs/functions/schedule-functions