show snackbar on fcm notification on every screen

The problem is with registering scaffolds for your NotificationManager widget since every time a new scaffold is added to the stack for a new screen, you need to register that screen's scaffold in the NotificationManager. This is because the line:

Scaffold.of(_context).showSnackBar(snackBar);

in your NoticicationManager will only look up the widget tree until the first scaffold it finds and call it there. Since you call NotificationManger.init(context: context); in your HomeScreen widget and pass the context of the HomeScreen, it will only live inside that scaffold. So, if you navigate away from the HomeScreen to a new widget with a different scaffold it will not have the NotificationManager as a child.

To fix the issue be sure you call Fcm.initConfigure(); in the first page that loads for the app, and for any pages you navigate to call NotificationManger.init(context: context); in either the initState() method for stateful widgets to register the current scaffold of that page or if they are stateless widgets, you can add it in the build method before returning the scaffold.


Copying the same code on all screens may not be ideal. If you have to change something, you will have to change everything or you will see inconsistencies. For snackbars, you can use this library and solve your problem in literally 1 line of code:

on your onMessage method:

onMessage(message){
Get.snackbar("message", message); // this line
}

Yes, the snackbar will be displayed regardless of the screen the user is on, and you won't need the scaffold's context, nor any context, just call the library method and that's it.

lib: https://pub.dev/packages/get