Flutter showSnackBar called on null

Viewed 16844

I am trying to show a snack bar in a tabbed flutter app as follows:

  var scaffoldKey = new GlobalKey<ScaffoldState>();
    scaffoldKey.currentState
      .showSnackBar(new SnackBar(
        content: new Text("This is a message")
      );
  });

But I am getting the error:

NoSuchMethodError: The method 'showSnackBar' was called on null.

In the main.dart file I initialize the app as follows:

runApp(new MaterialApp(...));

And then the snackBar is being called in home.dart which has a tabbed interface:

Widget build (BuildContext context) => new Scaffold(...);

So I'm a bit confused on which scaffold to call the snackbar on, and how, and also why scaffoldKey.currentState is null.

3 Answers

You need to pass Key to Scaffold Widget also.

Then you can call -scaffoldKey.currentState.showSnackBar

@override
  Widget build(BuildContext context) {
    return Scaffold(
      key: scaffoldKey,
      .....

If you are inside a widget that does not has directly the return Scaffold(...) widget, you can do this:

Scaffold.of(context).showSnackBar(
 SnackBar(content: Text("Hello from snackbar",
 textAlign: TextAlign.center, style: TextStyle(fontSize: 14.0, fontWeight: 
 FontWeight.bold),), duration: Duration(seconds: 3), backgroundColor: Colors.blue,)
);

There is no need to create an extra Scaffold widget because the showSnackBar() method requires one, you can reuse.

     final GlobalKey<ScaffoldState> _scaffoldstate= new GlobalKey<ScaffoldState>();
 void _showbar(){
   _scaffoldstate.currentState.showSnackBar(new SnackBar(content: new Text('Hello world')));
 }

In case you are here and the compiler throws this error

The method 'showSnackBar' can't be unconditionally invoked because the receiver can be 'null'.

just add ! in front of currentState.

_scaffoldstate.currentState!.showSnackBar(new SnackBar(content: new Text('Hello world')));
Related