如何在Flutter App中处理onPause/onResume? [英] How to handle onPause/onResume in Flutter App?
问题描述
我是Dart/Flutter的新手,并且想构建一个简单的应用,其中LinearProgressBar每秒更新一次.
I'm new to Dart/Flutter and would like to build a simple app where a LinearProgressBar gets updated every second.
在不花太多时间编写实际代码的情况下,我可以进行以下设置.
Without getting too much into the actual code, I have the following setup working.
- 基于经过时间计算进度的函数.
- 显示进度的LinearProgressBar.
- 一个定期的计时器,它重新计算进度并每秒更新进度栏.
- 我每次都调试打印"tick",重新计算就完成了.
一切正常,但有一个例外.当我在Android设备上的后台移动应用程序时,滴答声"会一直打印.
Everything is working as expected with one exception. The 'tick' keeps getting printed when I move the app in the background on my Android device.
在本机Android上,当触发"onPause"事件时,我会取消定期计时器.
On native Android, I would cancel my periodic Timer when the 'onPause' event is triggered.
Flutter中有类似的东西吗?我所能找到的只是"initState"和"dispose".但是,将应用程序移至后台时,不会调用Dispose.
Is there something similar in Flutter? All I could find was 'initState' and 'dispose'. Dispose, however, does not get called when moving the app to background.
我不希望计时器一直在后台计时.
I don't want the timer to keep ticking in the background.
在研究中,我发现了这个堆栈溢出问题 onresume-and-pause -随风飘扬的小工具.答案是建议使用 TickerProviderStateMixin .
On my research, I found this Stack Overflow question onresume-and-onpause-for-widgets-on-flutter. It's answer suggests using TickerProviderStateMixin.
我以下列方式使用它.
class _BarItemState extends State<BarItem> with SingleTickerProviderStateMixin {
Ticker ticker;
num progress = 1.0;
@override
void initState() {
super.initState();
ticker = createTicker((duration) => setState(() {
debugPrint('tick');
progress = duration.inSeconds / 30;
}))
..start();
}
// other stuff omitted
}
它正在工作,但我仍然不满意.
It is working, but I'm still not satisfied.
原因是,股票报价回调现在每隔几毫秒而不是每秒一次被调用.在我看来,这似乎是对资源的浪费(我不需要平滑的动画),...我是否使事情过于复杂了?
The reason is, that the ticker callback is getting now called every few milliseconds instead of once a second. This seems to me like a waste of resources (I don't need a smooth animation), ... am I overcomplicating things?
即使我的用例似乎不需要它,我仍然想知道:
Even if it seems that I don't need it for my use case, I still would like to know:
如何自行处理onPause/onResume事件?
How to handle the onPause/onResume events on my own?
推荐答案
您可以覆盖WidgetBindingObserver
界面的didChangeAppLifecycleState
以接收有关 app生命周期更改的通知.
You can override the didChangeAppLifecycleState
of the WidgetBindingObserver
interface to receive notifications for app lifecycle changes.
这篇关于如何在Flutter App中处理onPause/onResume?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!