Daniel Tjuatja
Daniel Tjuatja

Reputation: 41

Global scaffold to show Snackbar in flutter

I'm trying to structure a flutter app with a single global scaffold to show and interact with a snackbar over every widgets.

My current solution is to have a nested material app with the top one as a host to a scaffold with a global scaffold key. Which is probably not a good practice.

Here is the current code:

return MaterialApp(
      home: Scaffold(
        key: scaffoldKey,
        body: MaterialApp(
          title: 'MyApp',
          builder: (context, navigator) {
            return navigator
          },
        ),
      ),
    );

Is there any other solution without having to resort to nested material app? Thanks in advance!

Upvotes: 4

Views: 4431

Answers (2)

George Chailazopoulos
George Chailazopoulos

Reputation: 470

You could use the MaterialApp builder to "automatically" wrap all your routes in a Scaffold like this.

 MaterialApp(
            title: 'MyApp',
            builder: (context, child) =>
                Scaffold(appBar: null, body: child));

Then you can normally use Scaffold.of(context) or a global scaffoldKey

Upvotes: 1

vipin agrahari
vipin agrahari

Reputation: 2911

If your root widget contains a scaffold then all the child widgets can show a snackbar using.

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

Upvotes: 1

Related Questions