I'm trying to show a SnackBar when i receive a push notification.
I've followed the recipe on the documentation, but i'm not able to make the SnackBar works when i'm in a route which is different from the one in which i implement my BlocListener even if debugging it i can see that it gets actually called correctly.
I imagine this happens because since my page have another Scaffold then the Scaffold.of(context).showSnackbar(mySnackBar) is not getting the correct Scaffold, but the one of the app.dart which is not the first page in the stack at the moment.
The only workaround i can think of is to basically create a BlocListener in every other route of my app, and copy paste this code all around, which is not very scalable nor elegant.
There are other better approaches i'm not aware of?
How do you handle the display of a "global" widget using flutter_bloc?
app.dart
class _AppState extends State<App> {
//...some more code..
@override
Widget build(BuildContext context) {
return BlocProviderTree(
blocProviders: [
BlocProvider<AuthBloc>(bloc: _authBloc),
BlocProvider<NotificationsBloc>(bloc: _notificationsBloc),
],
child: MaterialApp(
routes: {
'/home': (context) => HomePage(),
'/profile': (context) => ProfilePage(),
},
home: Scaffold(
body: BlocListener(
bloc: _notificationsBloc,
listener: (BuildContext context, NotificationsState state) {
if (state is NotificationsLoaded) {
final snackBar = NotificationSnackBar(
title: state.notification.title,
body: state.notification.body,
onClose: () {
debugPrint('Close');
},
);
Scaffold.of(context).showSnackBar(snackBar);
}
},
child: BlocBuilder<AuthEvent, AuthState>(
bloc: _authBloc,
builder: (BuildContext context, AuthState state) {
//...some more code...
if (state is AuthAuthenticated) {
_notificationsBloc.dispatch(Setup());
return HomePage();
}
}
//...some more code...
},
)),
),
),
);
}
}
Hi @nerder 馃憢
Thanks for opening an issue!
Regarding your question, I don't think this is a bloc-specific issue.
The SnackBar component is intended to be scoped to a specific Scaffold and you shouldn't have a global Snackbar.
As you pointed out, in your case you have multiple Scaffolds and are trying to trigger an action against a specific one rather than the closest one. I would recommend looking into overlays if you want to have a widget that is rendered on top of all of the UI from anywhere in the application.
Hope that helps 馃憤
Most helpful comment
Hi @nerder 馃憢
Thanks for opening an issue!
Regarding your question, I don't think this is a bloc-specific issue.
The
SnackBarcomponent is intended to be scoped to a specificScaffoldand you shouldn't have a globalSnackbar.As you pointed out, in your case you have multiple
Scaffoldsand are trying to trigger an action against a specific one rather than the closest one. I would recommend looking into overlays if you want to have a widget that is rendered on top of all of the UI from anywhere in the application.Hope that helps 馃憤