how to check if app is in foreground flutter code example
Example 1: how to check Flutter app comes to foreground
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();
}
Example 2: flutter check if app is in foreground
class _MyHomePageState extends State<MyHomePage> with WidgetsBindingObserver {
late 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();
}
}