I'm trying to display a SnackBar
after performing an action from the AppBar
.
The AppBar
cannot be built from a builder so it can't access is Scaffold ancestor.
I know we can use a GlobalKey
object to access the context whenever we want, but I would like to know if there is a solution without using the GlobalKey
.
I found some github issues and pull-request, but I can't find a solution from them
=> https://github.com/flutter/flutter/issues/4581 and https://github.com/flutter/flutter/pull/9380
Some more context:
I have an Appbar
with a PopupMenuButton
, which have one item. When the user click on this item I display a dialog which the showDialog
method and if the user clicks on "ok" I want to display a SnackBar
Be sure to use a Builder widget as the root of the body parameter to make the Scaffold available to the context given to the Scaffold. of which is used to display the Snackbar. We also need to make the background of the Scaffold transparent to persist the translucent effect of the AlertDialog.
actions: This property takes in a list of widgets as a parameter to be displayed after the title if the AppBar is a row. title: This property usually takes in the main widget as a parameter to be displayed in the AppBar. backgroundColor: This property is used to add colors to the background of the Appbar.
You can use the Builder widget
Example:
Scaffold(
appBar: AppBar(
actions: <Widget>[
Builder(
builder: (BuildContext context) {
return IconButton(
icon: const Icon(Icons.message),
onPressed: () {
final snackBar = SnackBar(content: Text('Yay! A SnackBar!'));
Scaffold.of(context).showSnackBar(snackBar);
},
);
},
),
],
)
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With