How to close opened SnackBar on closing of screen?

728

The solution is simlple:

ScaffoldMessengerState snackbar;

void dispose() {
  snackbar.removeCurrentSnackbar();
  super.dispose();
}

void didChangeDependencies(BuildContext context) {
  super.didChangeDependencies(context);
  snackbar = ScaffoldMessenger.of(context);
}

Widget build(BuildContext context) {
  ...
  snackbar.showSnackbar(...);
  ...
}
Share:
728
BambinoUA
Author by

BambinoUA

Expirienced in: Dart/Flutter WinDev/WebDev/WinDev Mobile PHP Clarion for Windows Microsoft C#

Updated on December 12, 2022

Comments

  • BambinoUA
    BambinoUA over 1 year

    I have a BottomNavigationBar for managing various screens. SnackBar is opened on one screen and when I go to another screen, the Snackbar stays still opened. I need to close it immediately when I switch to the another screen. I understand that removeCurrentSnackBar() method must be called in dispose method but when I tried to do this I get the error: Looking up a deactivated widget's ancestor is unsafe. It looks like context is already disposed.

    So the question is in title.

    • Ajil O.
      Ajil O. almost 5 years
      Are you sure you're calling .removeCurrentSnackBar() before super.dispose()?
    • BambinoUA
      BambinoUA almost 5 years
      Yes. I place those line of code before super.dispose. Some message also said state is not stable in dispose method. I used global key for Scaffold but the value of currentState in dispose method is already null.
    • SardorbekR
      SardorbekR about 3 years
      @BambinoUA Have you found a solution for this? I am facing same issue now
    • BambinoUA
      BambinoUA about 3 years
      @SardobekR, see my answer.