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.
When you refresh the page, the entire app is destroyed and launched again. This is how the browser works, nothing specific to Flutter here. So the values of local variables are expected to disappear. The way navigation works today is by keeping the navigation stack in memory.
How to Detect the Closing of a Browser Tab. 1 If navigation entries have reload navigation type, the user reloaded the page. 2 If the tab count is decreased, the user closed a tab. 3 If the tab count is decreased AND the storage time difference is less than 50ms, the user probably closed the browser.
To understand a browser close, we need to first understand how a browser is closed. When a user closes the browser window, each tab within that browser is closed one after the other (based on my experiments, the delay in Chrome is about 1 ms on light to average load). Now, we know that a browser close will trigger beforeunload event handler.
You cannot control when user will refresh the web page and close it, but it’s important sometimes to display a confirmation alert before closing the Tab. The user may be mistakenly clicked the close button and lost some important data.
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
});
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
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With