I'm having an issue with Flutter routes and a duplicate GlobalKey in the widget tree.
My app does the following:
Screen_A -> Screen_B -> Screen_C
In each case, the navigation (->) is done via the following (where * is B or C):
Navigator.push(context, MaterialPageRoute(builder: (context) => Screen_*()));
I then navigate from Screen_C -> Screen_A
via:
Navigator.pushAndRemoveUntil(context,
MaterialPageRoute(builder: (context) => Screen_A()),
(Route<dynamic> route) => false);
Finally, I navigate from Screen_A -> Screen_B
using the original Navigator.push
method. I'm getting the following error:
'package:flutter/src/widgets/will_pop_scope.dart': Failed assertion: line 135 pos 12: 'route == ModalRoute.of(context)': is not true.
Exception caught by widgets library: Duplicate GlobalKey detected in widget tree.
For reference, Screen_B
is a form wherein I define a GlobalKey via:
GlobalKey<FormState> formKey = GlobalKey<FormState>();
I can't figure out why this is occurring. It appears where I define the GlobalKey and how I route is the proper way. Shouldn't Navigator.pushAndRemoveUntil
remove the route stack history, thereby removing the old GlobalKey in Screen_B
?
SOLVED: The solution turned out to to be where I was putting the GlobalKey declaration. I previously had it outside of my stateful widget like so:
GlobalKey<FormState> formKey = GlobalKey<FormState>();
class Screen_B extends StatefulWidget { (etc.) }
class _Screen_B extends State<Screen_B > { (etc.) }
But upon moving it into the State<Screen_B>, my issue was solved. Like so:
class Screen_B extends StatefulWidget { (etc.) }
class _Screen_B extends State<Screen_B > {
GlobalKey<FormState> formKey = GlobalKey<FormState>();
(etc.)
}
===== Additionally, as ikerfah noted above, using pushReplacement() would have worked as well from Screen_A -> Screen_B -> Screen_C.