How to handle back button in GoRouter for mobile and web at the same time

521 views Asked by At

According to GoRouter documentation,

GoRouter can push a screen onto the Navigator's history stack using context.push(), and can pop the current screen via context.pop(). However, imperative navigation is known to cause issues with the browser history.

So, on the web, we have to use .go(). Then, if we want to be able to go back with both the browser and in-app back buttons it's nice to call window.history.back();.

But that doesn't work on native mobile apps. So on apps, we have to use Navigator.of(context).maybePop();. But... that doesn't work if using .go() to navigate through the app, because it just closes the app.

So does that mean we should navigate with .go() on the web and .push() on mobile apps? Is there any other solution?

I tried looking for a solution on the official GoRouter documentation page and also on GoRouter's GitHub issue page, but I found nothing.

1

There are 1 answers

1
WebDesk Solution On

To navigate on the web, use context.go() and enable browser history by use window.history.back(). When it comes to mobile apps, user Navigator.of(context).push() for navigation. It is recommended to selectively choose the suitable method based on the platform using kIsWeb from dart:io.

Please check below code:

if (kIsWeb) {
    context.go('/your_screen');
    window.history.back();
  } else {
    Navigator.of(context).push(MaterialPageRoute(
      builder: (context) => YourScreen(),
    ));
  }