Search code examples
flutterdartdart-null-safetynull-safety

Unhandled Exception: Looking up a deactivated widget's ancestor is unsafe Navigator.push after migration to null safety


I have migrated all my packages of the project to null safety.

Due to some thinks that I have to handle on the Android (Kotlin), extending a third party library. After doing that now I receive the following error:

E/flutter (14210): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: Looking up a deactivated widget's ancestor is unsafe.
E/flutter (14210): At this point the state of the widget's element tree is no longer stable.
E/flutter (14210): 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.
E/flutter (14210): #0      Element._debugCheckStateIsActiveForAncestorLookup.<anonymous closure>
package:flutter/…/widgets/framework.dart:3944
E/flutter (14210): #1      Element._debugCheckStateIsActiveForAncestorLookup
package:flutter/…/widgets/framework.dart:3958
E/flutter (14210): #2      Element.findAncestorStateOfType
package:flutter/…/widgets/framework.dart:4005
E/flutter (14210): #3      Navigator.of
package:flutter/…/widgets/navigator.dart:2727
E/flutter (14210): #4      _PinCodeScreenState.build.<anonymous closure>.<anonymous closure>.<anonymous closure>.<anonymous closure>
package:vista/…/pin_code/pin_code.dart:274
E/flutter (14210): #5      _rootRunUnary (dart:async/zone.dart:1362:47)
E/flutter (14210): #6      _CustomZone.runUnary (dart:async/zone.dart:1265:19)
E/flutter (14210): <asynchronous suspension>

and I have the following code:

Navigator.push(context, MaterialPageRoute(builder: (context) => MyScreen(response: _validatioResponse)));

The above code gets called by a RawMaterialButton widget, onPressed


Solution

  • try this way

     SchedulerBinding.instance.addPostFrameCallback((_) {
                                  Navigator.pushNamedAndRemoveUntil(
                                      context, '/', (_) => false);
                                });