csells / go_router

The purpose of the go_router for Flutter is to use declarative routes to reduce complexity, regardless of the platform you're targeting (mobile, web, desktop), handling deep linking from Android, iOS and the web while still allowing an easy-to-use developer experience.
https://gorouter.dev
441 stars 96 forks source link

Duplicate GlobalKey detected in widget tree error when using global keys #243

Closed raduungurean closed 2 years ago

raduungurean commented 2 years ago

Hi @csells ,

Great package! However I'm struggling with an issue and I am not sure how to deal with it. When I'm using the same scaffold for two screens, when I move from screen A to screen B using this: GoRouter.of(context).go('/screen_b'); I'm getting the Duplicate GlobalKey detected in widget tree eror

I assume the previous screen is not fully disposed or so. Is there a solution for this?

Scaffold(
          key: GetIt.instance.get<GlobalKey<ScaffoldState>>(),
          appBar: hideAppBar(_router.location)
              ? const EmptyAppBar()
              : AppBar(
                  title: const Text('App title'),
                ),
          body: ScreenA/ScreenB

Thank you,

elias8 commented 2 years ago

Hi @raduungurean 👋,

It seems you have registered the GlobalKey<ScaffoldState> as a singleton in GetIt. So whenever you are trying to use the global key, GetIt will return the same global key and end up with multiple widgets trying to use the same global key somewhere in your widget tree.

If that is the case, you can fix it by changing the dependency registration from singleton to factory. But generally speaking, I don't see the necessity of using GetIt for this case in the first place. So I think it is better to put the key somewhere with the widget that is using it.

Hope that helps!