How to Check Whether Application is in Foreground or not in Flutter ?

· 2 min read
How to Check Whether Application is in Foreground or not in Flutter
How to Check Whether Application is in Foreground or not in Flutter

While Developing a Flutter Mobile Application it may happen that we need to perform a separate operation for Foreground and Background. So we need to Check that Whether the Application is in  Foreground or not.

How to Check Whether Application is in Foreground or not in Flutter?

In your State<…> class you need to implement the 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();
  }
}

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;
   }

Conclusion:

In this article, So we have been through How to Check that Whether the Application is in  Foreground or not.

Keep Learning !!! Keep Fluttering !!!

Still, need a Support for Flutter Development? Do let us know.

FlutterAgency.com is our portal Platform dedicated to Flutter Technology and Flutter Developers. The portal is full of cool resources from Flutter like Flutter Widget GuideFlutter ProjectsCode libs and etc.

FlutterAgency.com is one of the most popular online portal dedicated to Flutter Technology and daily thousands of unique visitors come to this portal to enhance their knowledge on Flutter.

Leave a Reply