I am running into a globalKey
error after I navigate from Screen A
to Screen B
and click a \"Cancel\" button to go back to Scree
In my case I wanted to use the static GlobalKey<ScaffoldState> _scaffoldKey
but when I used the same widget multiple times it gave this duplicate error.
I wanted to give it a unique string and still use this scaffold state. So I ended up using:
static GlobalObjectKey<ScaffoldState> _scaffoldKey
and in the initState
:
_scaffoldKey = new GlobalObjectKey<ScaffoldState>(id);
Edit:
Actually, silly me. I just simply removed the static
and made it GlobalKey
again :)
I had this issue too. I had a four screen bottom tabbed application and a 'logout' method. However, that logout method was calling a pushReplacementNamed. This prevented the class that held the global keys (different from the logout function) from calling dispose.
The resolution was to change pushReplacementNamed with popAndPushNamed to get back to my 'login' screen.
I am not sure why no one has mentioned this yet but, in my case, I simply changed a widget from Stateful to Stateless. To fix the error, you have to restart the application instead of doing a hot reload.
Best way to solve that, which worked for me:
class _HomeScreenState extends State<HomeScreen> {
GlobalKey<FormState> _homeKey = GlobalKey<FormState>(debugLabel: '_homeScreenkey');
@override
Widget build(BuildContext context) {
return Container(
key: _homeKey,
);
}
}
I also had a similar error. My answer was that after I updated Flutter some widgets no longer had child or children properties. In my case it was the CircleAvatar. The build doesn't error out initially, but when navigating back and forth through the app it will fail.
*Please review all widgets that require a child then review the updated documentation and make sure you're parameters are still correct.
Thanks to Gunter's commments, I determined that this is because the Screens are not being properly disposed.
Flutter's pushReplacement makes a call to Route.dispose
which will ultimately dispose the screen.
I am still unsure as to this comes into play:
widget must be inserted into the new location in the same animation frame
I'm not sure what situation would benefit from such trickery. However, my problem is solved. I just need to make a call to pop or replace.
Here are the available options:
push
from A
to B
and just Navigator.pop
from B
pushReplacement
from A
to B
and from B
to A
I've recently started playing with Fluro for routing and there are a few more ways to to handle these situations (Note the optional argument replace):
router.navigateTo(context, route, replace: false)
from A
to B
and Navigator.pop
from B
router.navigateTo(context, route, replace: true)
from A
to B
the same from B
to A
(the key is replace: true
)