title: Flutter: How to close SnackBar when navigating away?
body: <p>I have an issue. I have a &quot;details&quot; page which can display a <code>SnackBar</code> via <code>ScaffoldMessenger</code>.
  This snackbar does not hide, its duration is set to long time because it's supposed to stay visible for a long time or until it's dismissed by user <strong>or by navigating away from the view.</strong></p>
  <p>The last part is the one I'm having issue with. In my <code>dispose</code> method I try to call <code>ScaffoldMessenger.of(_scaffoldKey.currentContext!).hideCurrentSnackBar()</code> but this does not work and throws error that it can't access the context.
  I suspect it's because the context associated with the key is also the same context that is being removed from the widget tree since I'm navigating away from it (by using back button).</p>
  <p>I do not want to handle removing of the snackbar in other views. I know I could probably call <code>ScaffoldMessenger.of(context).clearAllSnackBars()</code> every time I would navigate to them but I don't like it for architectural reasons:</p>
  <ol>
  <li>The &quot;detail&quot; view <em>owns</em> the snackbar because it's responsible for creating it. It should be also responsible for disposing of it.</li>
  <li>In future I might reorganize my views and then I have to remember to
  clear the snackbar everywhere. The example I gave you is constrained
  example but imagine there's accessible sidebar leading to many
  different views. It would mean adding this code to all those views.</li>
  </ol>
  <p>So I really want to somehow remove that snackbar when disposing of the <code>DetailPage</code> view. How can I achieve this?</p>
  <p>Link to <a href="https://dartpad.dev/?null_safety=true&amp;id=2f7be46f96ffd31c647a05d23fbf1b07" rel="nofollow noreferrer">dartpad.dev</a></p>
  <pre class="lang-dart prettyprint-override"><code>import 'package:flutter/material.dart';
  
  void main() {
    runApp(App());
  }
  
  class App extends StatelessWidget {
    @override
    Widget build(BuildContext context) {
      return MaterialApp(home: const HomePage(), routes: {
        '/detail': (_) =&gt; const DetailPage(),
      });
    }
  }
  
  class HomePage extends StatelessWidget {
    const HomePage({
      Key? key,
    }) : super(key: key);
  
    @override
    Widget build(BuildContext context) {
      return Scaffold(
        appBar: AppBar(title: const Text('Home')),
        body: SizedBox.expand(
          child: TextButton(
            child: const Text('See detail'),
            onPressed: () {
              Navigator.pushNamed(context, '/detail');
            },
          ),
        ),
      );
    }
  }
  
  class DetailPage extends StatefulWidget {
    const DetailPage({
      Key? key,
    }) : super(key: key);
  
    @override
    _DetailPageState createState() =&gt; _DetailPageState();
  }
  
  class _DetailPageState extends State&lt;DetailPage&gt; {
    final GlobalKey&lt;ScaffoldState&gt; _scaffoldKey = GlobalKey&lt;ScaffoldState&gt;();
  
    @override
    void initState() {
      super.initState();
      WidgetsBinding.instance!.addPostFrameCallback((_) {
        ScaffoldMessenger.of(_scaffoldKey.currentContext!).showSnackBar(SnackBar(
          content: const Text('Entered detail page'),
          duration: const Duration(days: 1),
          action: SnackBarAction(
              label: 'Close',
              onPressed: () {
                ScaffoldMessenger.of(_scaffoldKey.currentContext!)
                    .hideCurrentSnackBar();
              }),
        ));
      });
    }
  
    @override
    void dispose() {
      ScaffoldMessenger.of(_scaffoldKey.currentContext!).hideCurrentSnackBar();
      super.dispose();
    }
  
    @override
    Widget build(BuildContext context) {
      return Scaffold(
        key: _scaffoldKey,
        appBar: AppBar(title: const Text('Detail')),
        body: const SizedBox.expand(
          child: Center(child: Text('Detail page')),
        ),
      );
    }
  }
  </code></pre>