简体   繁体   中英

Flutter + FCM: Cant change UI in onMessage method

I use Firebase FCM in Flutter to inform the App when a message is received. The initState method of my widget (which returns a Scaffold) looks like this:

@override
void initState() {
super.initState();

FcmService(_fcm).saveDeviceToken();

_fcm.configure(
  onMessage: (Map<String, dynamic> message) async {
    print('Notification received');

    final snackbar = SnackBar(
      content: Text(message['notification']['title']),
      action: SnackBarAction(
        label: 'Go',
        onPressed: () => null,
      ),
    );
    Scaffold.of(context).showSnackBar(snackbar);
  },
);
}

When a message is sent to the device, the print is executed, so everything should work fine, but the SnackBar doesn't show up. I also tried showing an AlertDialog or just using setState and changing a variable displayed on a label to test whether this is a SnackBar exclusive thing, but it isn't. Nothing changed, although the method is executed.

You cannot get a scaffoldstate from initstate, try using a future delay method if calling it in the initstate is mandate for you or simply call it from build method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM