Update - Resolved
Somehow, this problem was happening due to toggling the visibility of the iFrame div
on the parent website side of things, rather than any EventListener
/State
issue on the Flutter slide.
I'm following Flutter Web listen to Events posted through iFrame and trying to send a message from a parent website to a child Flutter app in an iFrame.
The message is working correctly and I can print the value inside the Flutter app; however, I can't call setState
from my event listener successfully and use the message value elsewhere.
The website code is the same as in the link above. In my Flutter app:
class HomePageWidget extends StatefulWidget {
const HomePageWidget({Key? key}) : super(key: key);
@override
_HomePageWidgetState createState() => _HomePageWidgetState();
}
class _HomePageWidgetState extends State<HomePageWidget> {
String? messageValue;
@override
void initState() {
html.window.addEventListener('message', listen, true);
super.initState();
}
@override
void dispose() {
html.window.removeEventListener('message', listen, true);
super.dispose();
}
void listen(html.Event event) {
var data = (event as html.MessageEvent).data;
final received = data['message'];
// This works successfully.
print(received);
// This does not.
setState(() {
messageValue = received;
});
}
@override
Widget build(BuildContext context) {
return Text(messageValue ?? 'no message');
}
}
I've verified that I'm receiving the message in my listen()
method. I'm expecting to be able to call setState
from my listen()
method too; is there an issue with state scope this since it's being called from the stateful widget's init
method?