0

I am getting the error

"Exception has occurred. FlutterError (Looking up a deactivated widget's ancestor is unsafe. At this point the state of the widget's element tree is no longer stable. 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.)"

in the piece of code

Navigator.of(context, 
  rootNavigator: true).pop(
     MaterialPageRoute(
        builder: (context) => HomePage()));

and is trying to resolve using this solution

So i did this

MyGlobals myGlobals = MyGlobals();

class MyGlobals {
  late GlobalKey _scaffoldKey;
  MyGlobals() {
    _scaffoldKey = GlobalKey();
  }
  GlobalKey get scaffoldKey => _scaffoldKey;
}

and pointed the scaffoldKey to the scaffold

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

And then used it in the navigator

 Navigator.of(myGlobals.scaffoldKey.currentContext,
                                rootNavigator: true)
                            .pop(MaterialPageRoute(
                                builder: (context) => HomePage()));

Now i get a compiler error on myGlobals.scaffoldKey.currentContext

The argument type 'BuildContext?' can't be assigned to the parameter type 'BuildContext'.

Now the GlobalKey class does mark BuildContext nullable and the widgets expects the context not nullable. Is this the correct way to do this?

asb
  • 697
  • 2
  • 5
  • 19
  • The correct solution is to not try and look up a `Navigator` of a widget that has been deactivated, i.e. removed from the widget tree. – Abion47 Jul 03 '21 at 04:05

0 Answers0