如何在 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-onpause-for-widgets-on-flutter.它的答案建议使用 TickerProviderStateMixin.
On my research, I found this Stack Overflow question onresume-and-onpause-for-widgets-on-flutter. It's answer suggests using TickerProviderStateMixin.
我是按照以下方式使用的.
I used it the following way.
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
来接收应用生命周期的通知 变化.
You can override the didChangeAppLifecycleState
of the WidgetBindingObserver
interface to receive notifications for app lifecycle changes.
这篇关于如何在 Flutter App 中处理 onPause/onResume?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!