Shady Aziza
Shady Aziza

Reputation: 53317

Show SnackBar from a custom Scaffold base

I am having difficulties trying to achieve a unified Scaffold theme. My initial thought was to cleanup my UI and reuse the code of the shareable elements of my scaffolding across the application. So now I have a base Scaffold with the default configuration that is used by any screen that builds MyScaffold. However, when I started to implement error handling I started to face this problem of accessing the context or the state of MyScaffold. So if I have a screen that makes use of the base Scaffold and it needs to show a SnackBar at some point, it would be something like:

class LoginScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MyScaffold(
      //custom configuration
    );


  }
  //Called somehwere
    void signIn() async{
      try{
        // await signIn
      }
      catch(e){
        // showSnackBar
      }
    }
}

However, I am unable to show the SnackBar because the conext and the state of LoginScreen does not contain a real Scaffold but MyScaffold is the correct widget to handle showing a SnackBar. Is this achievable or should I drop my base Scaffold and re-write the common configuration parts. One example for what I mean by configurations is that I style my Scaffold differently based on the Platform.

One thing I have tried is using a GlobalKey

final GlobalKey<ScaffoldState> _authScaffold =GlobalKey<ScaffoldState>();

 return MyScaffold(
      key:_authScaffold ,...

and on the same widget I call

 _authScaffold.currentState.showSnackBar(SnackBar(content:Text(message)));

but I get

 NoSuchMethodError: The method 'showSnackBar' was called on null.
E/flutter ( 1337): Receiver: null

Upvotes: 0

Views: 519

Answers (1)

rmtmckenzie
rmtmckenzie

Reputation: 40433

As Rémi answered in the comments, moving the widgets under your MyScaffold is the best way of doing it, as that way the BuildContext you're using is a context that includes the scaffold.

If needed, you can use a Builder widget to get a context lower down in the tree without having to make a new widget class.

But to address the reason why GlobalKey wan't working for you - I have to guess a little as you didn't include code for your MyScaffold, but since you were passing key to your MyScaffold, I assume you weren't passing it down further as both Stateful and Stateless widgets have a key parameter. What you should have been doing is passing a different value i.e. scaffoldKey, and then within your MyWidget's build function passing the scaffoldKey to Scaffold(key: scaffoldKey). But using globalkeys is generally avoidable and not recommended.

Upvotes: 1

Related Questions