14

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.

Ross Patterson
  • 257
  • 1
  • 3
  • 10

2 Answers2

18

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
});
Bharath
  • 196
  • 1
  • 4
3

Just use OnBeforeUnload or OnUnload. to me it worked without async, I recon it is because the window doesn't wait to be closed it just closes. if you want to change something in your db when the user exits tab or refreshes, you should call a method on the back thread so that it will keep on running and finish the task even after window closed/tab closed/refresh.

html.window.onBeforeUnload.listen((event) {
   // change something in db
});