I am working on the Flutter web and using go_router for navigation.
Expectation: From the initial route, When the user tries to navigate back using the browser back button or reload the page, an alert box should be displayed and ask, "Are You sure you want to exit?" Kind of message and on User interaction page allows to exit or stay on the same page.
Tried Approaches:
1. WillPopScope:
I have added the WillPopScope widget on HomeRoute Widget to detect popCallBack. but Somehow It is not being triggered on the back button pressed because might I have used go_router for Navigation.
By executing the Below statement I am not able to print the log on the console onBack event.
return WillPopScope(
onWillPop: () async {
print("on Will Pop is Called");
return false;
},
child: PaintScaffold(...)
);
BackButtonDispatcher of MaterialApp.router is only applicable on android, not on the web. So it is not going to work. Reference of it.
2. onBeforeUnload listener
I have tried to add the script on the index.html file to detect the onBeforeUnload event. But Its behavior is unexpected. It works fine in the chrome browser but in safari, it does not show an alert box on backButton pressed. But work on reloading the page.
on the iOS safari browser, onBeforeUnload is not being triggered in any of the cases when the page unloads.
<script>
window.addEventListener('load', function(ev) {
// Download main.dart.js
_flutter.loader.loadEntrypoint({
serviceWorker: {
serviceWorkerVersion: serviceWorkerVersion,
}
}).then(function(engineInitializer) {
return engineInitializer.initializeEngine();
}).then(function(appRunner) {
return appRunner.runApp();
});
});
window.onunload = window.onbeforeunload = function(){
return 'Are you sure you want to leave?';
};
</script>
So Is there any other approach to resolve this issue when the user tries to exit the page then it will show an alert box to ask for confirmation?
Thank you.