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?
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?
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?
WidgetsBindingObserver
the errors are gone. I'll test it now. –
Nickelous didChangeAppLifecycleState()
still runs. –
Nickelous window.addEventListener('visibilitychange', onVisibilityChange);
with what you edited in your answer? Thanks for the help! –
Nickelous static void onFocus(Event e) { ... }
. The catch is you can't call didChangeAppLifecycleState now because that's non-static. You'll have to work around that –
Bourbon onFocus()
and onBlur()
I add an if
check. It looks something like if (active) {...}
. That seemed to fix the problem for me without having to make the methods static so that I don't have to work around the problem of not being able to call didChangeAppLifecycleState
. That seemed to fix the dispose issue but also works when hot restarting. I think it's a better fix than the static with the only problem being that it leaks memory and might not be very performant on larger scale apps. –
Nickelous Additionally, there is a flutter package that detects if Web app is refreshed or reloaded. You can take a look at flutterwebapp_reload_detector
© 2022 - 2024 — McMap. All rights reserved.
onVisbilityChange
? – Nickelous