0

when snackbar is being displayed on screen and at the same time if back button is pressed, it throws error in console in flutter / dart

I have removed snackbar by using

return WillPopScope(
  onWillPop: () async {
    ScaffoldMessenger.of(context).removeCurrentSnackBar();
    return true;
  },
child: Scaffold(...

but it is also not working.

error log is as:

E/flutter (13058): [ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: Looking up a deactivated widget's ancestor is unsafe.
E/flutter (13058): At this point the state of the widget's element tree is no longer stable.
E/flutter (13058): To safely refer to a widget's ancestor in its dispose() method, save a reference to the ancestor by calling dependOnInheritedWidgetOfExactType() in the widget's didChangeDependencies() method.

How can I fix this issue?

Kamlesh
  • 5,233
  • 39
  • 50

1 Answers1

0

As I can see from your logs, this issue is because the Context is not being passed to the WillPopScope widget correctly because it is disposed off

What you can do is

Declare a global variable

final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();

Then register this _scaffoldKey on your Scaffold like so

 @override
    Widget build(BuildContext context) {
     return Scaffold(
       key: _scaffoldKey,
       ...

Now whenever you need the access to this context you can use _scaffoldKey.currentContext such as in the ScaffoldMessenger.of.. part

This should fix your issue

gtxtreme
  • 1,830
  • 1
  • 13
  • 25