[英]How to handle onPause/onResume in Flutter App?
I'm new to Dart/Flutter and would like to build a simple app where a LinearProgressBar gets updated every second. 我是Dart / Flutter的新手,想建立一个简单的应用程序,其中LinearProgressBar每秒都会更新。
Without getting too much into the actual code, I have the following setup working. 没有太多的实际代码,我有以下设置工作。
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设备的后台移动应用程序时,'tick'会继续打印。
On native Android, I would cancel my periodic Timer when the 'onPause' event is triggered. 在原生Android上,当触发'onPause'事件时,我会取消我的定期计时器。
Is there something similar in Flutter? Flutter有类似的东西吗? All I could find was 'initState' and 'dispose'. 我能找到的只是'initState'和'dispose'。 Dispose, however, does not get called when moving the app to background. 但是,在将应用程序移动到后台时,不会调用Dispose。
I don't want the timer to keep ticking in the background. 我不希望计时器在后台继续滴答作响。
On my research, I found this Stack Overflow question onresume-and-onpause-for-widgets-on-flutter . 在我的研究中,我发现这个Stack Overflow问题onresume-and-onpause-for-widgets-on-flutter 。 It's answer suggests using TickerProviderStateMixin . 它的答案建议使用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: 即使我的用例似乎不需要它,我仍然想知道:
How to handle the onPause/onResume events on my own? 如何自己处理onPause / onResume事件?
You can use lifecycle channel from SystemChannels . 您可以使用SystemChannels的 生命周期通道。
Example: 例:
SystemChannels.lifecycle.setMessageHandler((msg){
debugPrint('SystemChannels> $msg');
});
Output: 输出:
I/flutter ( 3672): SystemChannels> AppLifecycleState.paused
I/flutter ( 3672): SystemChannels> AppLifecycleState.resumed
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.