Search code examples
flutterflutter-web

Flutter Web: How to detect AppLifeCycleState changes


I tested out the AppLifeCycleState on flutter web and it didn't work while it worked on mobile platforms.

This is an issue that is being worked on.

I was wondering if anyone knew any workarounds or packages which could do this?


Solution

  • Here is my workaround

    import 'dart:html';
    import 'package:flutter/foundation.dart';
    
      // inside your State class
    
      @override
      void initState() {
        super.initState();
        if (kIsWeb) {
          window.addEventListener('focus', onFocus);
          window.addEventListener('blur', onBlur);
        } else {
          WidgetsBinding.instance!.addObserver(this);
        }
      }
    
      @override
      void dispose() {
        if (kIsWeb) {
          window.removeEventListener('focus', onFocus);
          window.removeEventListener('blur', onBlur);
        } else {
          WidgetsBinding.instance!.removeObserver(this);
        }
        super.dispose();
      }
    
      void onFocus(Event e) {
        didChangeAppLifecycleState(AppLifecycleState.resumed);
      }
    
      void onBlur(Event e) {
        didChangeAppLifecycleState(AppLifecycleState.paused);
      }
    
      @override
      void didChangeAppLifecycleState(AppLifecycleState state) {
        // do your thing
      }
    

    Basically you hook into the browser's visibility API and invoke the life cycle callback yourself.

    See also How to detect if flutter website is running in the background of browser?