Search code examples
flutterdartflutter-web

Flutter Web: Detect browser/tab close or refresh?


With Flutter Android and iOS modules you can use AppLifeCycleState to detect when the app is put into the background.

Is there something similar for Flutter Web where I can detect the browser/tab closing or refreshing?

I essentially want to run a Firestore command if the person closes their browser or refreshes.


Solution

  • You can use the function "onBeforeUnload" to check if the tab is being closed. It might detect page refresh also.

    import 'dart:html' as html;
    html.window.onBeforeUnload.listen((event) async{
      // do something
    });
    

    or

    import 'dart:html' as html;
    html.window.onUnload.listen((event) async{
      // do something
    });