How do I check if the Flutter application is in the foreground or not?

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
  void 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.

Leave a Comment