如何检查 Flutter 应用程序是否在前台? [英] How do I check if the Flutter application is in the foreground or not?
本文介绍了如何检查 Flutter 应用程序是否在前台?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我不想在应用程序处于前台时显示通知.如何查看应用的实时状态?
I don't want to show notification when the app is in foreground. How can I check live state of my app?
推荐答案
在你的 State<...> 类中你需要实现 WidgetsBindingObserver 接口并监听小部件状态变化.像这样:
In your State<...> class you need to implement WidgetsBindingObserver interface and listen for widget state changes. Something like this:
class _MyHomePageState extends State<MyHomePage> with WidgetsBindingObserver {
AppLifecycleState _notification;
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
setState(() {
_notification = state;
});
}
@override
initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
...
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
super.dispose();
}
}
然后当您想知道状态是什么时,请检查 _notification.index 属性._notification == null => 没有发生状态变化,0 - 恢复,1 - 不活动,2 - 暂停.
Then when you want to know what is the state, check _notification.index property. _notification == null => no state changes happened, 0 - resumed, 1 - inactive, 2 - paused.
这篇关于如何检查 Flutter 应用程序是否在前台?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文