Reputation: 13202
There are many times where we would have had separation of concerns when it comes to UI code and business logic. This is reflected in most of the state management solutions that we use in Flutter.
In many of the state management solutions where the business logic is outside the view file ( widget file) , there are cases where we want to show the snackbar based on the logic in flutter.
But to show a Snackbar
we first need a context object. I have used a NavigatorState to navigate without context. But I don't know if there is a way to show SnackBar
without context.
Can someone provide a solution for this ?
Also it would be very helpful if you could provide a Utility method that manages the state internally and whenever user wants to show snackbar would just call that utility method from his logical part of code.
Upvotes: 2
Views: 2419
Reputation: 299
You can specify scaffoldMessengerKey
as a property of MaterialApp
and then ScaffoldMessenger
can be directly used without BuildContext
.
I think you can do the same way as navigatorKey
.
ref: https://api.flutter.dev/flutter/material/MaterialApp/scaffoldMessengerKey.html
Check this answer for more details on how to implement this into your application, with some code examples.
Upvotes: 2
Reputation: 1003
You definitelly can show a piece of information without a context, something similar to a snackbar
, however, it is not a snackbar
.
If you use the package Get, you can navigate without context
, open dialogs
, snackbars
or bottomsheets
from anywhere in your code. However, the snackbars
in particular have some issues.
As it doesn't check for a Scaffold
, the snackbar
is shown directly in the bottom of your screen. This means that if you have a BottomNavigationBar
, it will be covered or partially covered by it.
It also means that if you have a FloatingActionButton
, it won't be responsive to the snackbar
position, as opossed to the normal snackbar
.
So to sum up, with Get, you can have snackbars
without context
but you will have to make some sacrifices in your UI.
Example
final bottomSnackBar = GetBar(
isDismissible: false,
showProgressIndicator: true,
message: 'Processing...',
);
bottomSnackBar.show();
somethingAsync().then((_) => bottomSnackBar.hide());
Upvotes: 0