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(...);
...
}
Author by
BambinoUA
Expirienced in: Dart/Flutter WinDev/WebDev/WinDev Mobile PHP Clarion for Windows Microsoft C#
Updated on December 12, 2022Comments
-
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, theSnackbar
stays still opened. I need to close it immediately when I switch to the another screen. I understand thatremoveCurrentSnackBar()
method must be called indispose
method but when I tried to do this I get the error:Looking up a deactivated widget's ancestor is unsafe
. It looks likecontext
is already disposed.So the question is in title.
-
Ajil O. almost 5 yearsAre you sure you're calling
.removeCurrentSnackBar()
beforesuper.dispose()
? -
BambinoUA almost 5 yearsYes. 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 ofcurrentState
indispose
method is already null. -
SardorbekR about 3 years@BambinoUA Have you found a solution for this? I am facing same issue now
-
BambinoUA about 3 years@SardobekR, see my answer.
-