Display SnackBar in Flutter
<p>I want to display a <strong>simple <code>SnackBar</code> inside Flutter</strong>'s Stateful widget. My application creates new instance of <em><code>MaterialApp</code></em> with a stateful widget called <em><code>MyHomePage</code></em>.</p>
<p>I try to show the <strong>SnackBar</strong> in <code>showSnackBar()</code> method. But it fails with <em><code>The method showSnackBar was called on null</code></em>.</p>
<p>What's wrong with this code?</p>
<pre><code>class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter',
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: new MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key}) : super(key: key);

  @override
  _MyHomePageState createState() =&gt; new _MyHomePageState();
}

class _MyHomePageState extends State&lt;MyHomePage&gt; {

  final GlobalKey&lt;ScaffoldState&gt; _scaffoldKey = new GlobalKey&lt;ScaffoldState&gt;();

  @override
  void initState() {
    super.initState();
    showInSnackBar(&quot;Some text&quot;);
  }

  @override
  Widget build(BuildContext context) {
    return new Padding(
            key: _scaffoldKey,
            padding: const EdgeInsets.all(16.0),
            child: new Text(&quot;Simple Text&quot;)
    );
  }

  void showInSnackBar(String value) {
    _scaffoldKey.currentState.showSnackBar(new SnackBar(
        content: new Text(value)
    ));
  }
}
</code></pre>
<p><strong>SOLUTION:</strong></p>
<pre><code>class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
        title: 'Flutter',
        theme: new ThemeData(
            primarySwatch: Colors.blue,
        ),
        home: new Scaffold(body: new MyHomePage()),
      );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key}) : super(key: key);

  @override
  _MyHomePageState createState() =&gt; new _MyHomePageState();
}

class _MyHomePageState extends State&lt;MyHomePage&gt; {

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    showInSnackBar(&quot;Some text&quot;);
    return new Padding(
        padding: const EdgeInsets.all(16.0),
        child: new Scaffold(
          body: new Text(&quot;Simple Text&quot;)
        )
    );
  }

  void showInSnackBar(String value) {
    Scaffold.of(context).showSnackBar(new SnackBar(
        content: new Text(value)
    ));
  }
}
</code></pre>