Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter: How to display a snackbar from an appbar action

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

like image 804
Quentin Avatar asked Nov 28 '18 19:11

Quentin


People also ask

How do you show SnackBar over dialog in Flutter?

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.

How do I use actions in AppBar Flutter?

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.


1 Answers

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);
            },
          );
        },
      ),
    ],
  )
);
like image 67
Migo Avatar answered Sep 27 '22 22:09

Migo