I don\'t want to show notification when the app is in foreground. How can I check live state of my app?
Simply create a bool
variable which will keep track of all your background/foreground stuff.
Full code:
class _HomePageState extends State<HomePage> with WidgetsBindingObserver {
// This variable will tell you whether the application is in foreground or not.
bool _isInForeground = true;
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
super.didChangeAppLifecycleState(state);
_isInForeground = state == AppLifecycleState.resumed;
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
super.dispose();
}
@override
Widget build(BuildContext context) => Scaffold();
}
My Answer may be late but may be helpful for someone. I also faced this problem there is a plugin which works on both android and ios
https://pub.dev/packages/flutter_app_lock
Where you can put you desired lockscreen also it is very flexible.
Hope someone who stuck like me can get this easily done.
To extend on the above answer, you can use a switch statement to make it nice and neat:
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
switch(state){
case AppLifecycleState.resumed:
print("app in resumed");
break;
case AppLifecycleState.inactive:
print("app in inactive");
break;
case AppLifecycleState.paused:
print("app in paused");
break;
case AppLifecycleState.detached:
print("app in detached");
break;
}
}
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();
}
}
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.