Home > Software design >  GoRouter - Entering the url in the address bar doesn't only create the related page
GoRouter - Entering the url in the address bar doesn't only create the related page

Time:08-12

I'm writing a web flutter application with Persons screen

When I click on "Push", it pushed /persons/1 which is a transparent route that takes a 3 of the screen:

Person screen

This works well and I can still see the previous screen related to /persons behind the DrawerPage. And when I click on "Pop", it does remove the purple screen (as it should).


But what I don't understand is when I paste myself the URL in the browser's address bar (for example /persons/3), it also ends up with the purple page that takes 1/3 of the screen (this is fine), but for some reason, the grey screen (linked to /persons) is behind and I can pop to go to the previous page (/persons) when I click on "Pop".

How and why is this page built? How does flutter/GoRouter decide that when going to /persons/:id it should insert persons/ as the first page?

CodePudding user response:

This is how it works.

According to the documentation (https://gorouter.dev/sub-routes):

go_router will match the routes all the way down the tree of sub-routes to build up a stack of pages

The route /persons/id includes the screen /persons in the stack and that is why it is shown.

If you want a screen showing /persons/id without the stack, you could define a different route where /persons/id is the root. Like:

final router = GoRouter(
  routes: [
    GoRoute(
      path: '/',
      redirect: (_) => '/persons',
    ),
    GoRoute(
      path: '/persons',
      builder: (_, __) => const PersonsScreen(),
      routes: [
        GoRoute(
          path: ':id',
          pageBuilder: (_, __) => const DrawerPage(
            child: PersonScreen(),
          ),
        ),
      ],
    ),
    GoRoute(
      path: '/person/:id',
      pageBuilder: (_, __) => const DrawerPage(
        child: PersonScreen(),
      ),
    ),
  ],
);
  • Related