Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter showSnackBar called on null

Tags:

flutter

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.

like image 481
lilbiscuit Avatar asked Jan 06 '19 16:01

lilbiscuit


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,
      .....
like image 121
anmol.majhail Avatar answered Nov 20 '22 12:11

anmol.majhail


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.

like image 5
Juanma Menendez Avatar answered Nov 20 '22 11:11

Juanma Menendez


     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')));
like image 1
roropanda Avatar answered Nov 20 '22 12:11

roropanda