skip to Main Content

I have this code of router

final _router = GoRouter(
  routes: [
    GoRoute(
      path: '/',
      builder: (BuildContext context, GoRouterState state) {
        return const LoginScreenWidget();
      },
      routes: <RouteBase>[
        GoRoute(
          path: 'main',
          builder: (BuildContext context, GoRouterState state) {
            return const MainScreenWidget();
          },
          routes: [
            GoRoute(
              path: 'my-friends',
              builder: (BuildContext context, GoRouterState state) {
                return const FriendsScreenWidget();
              },
              routes: [
                GoRoute(
                  path: ':userId',
                  builder: (BuildContext context, GoRouterState state) {
                    return FriendProfileScreenWidget(
                      userId: state.params['userId'],
                    );
                  },
                  routes: [
                    GoRoute(
                      path: 'friends',
                      builder: (BuildContext context, GoRouterState state) {
                        return ProfileFriendsScreenWidget();
                      },
                    ),
                  ],
                ),
              ],
            ),
          ],
        ),
      ],
    ),
  ],
);

class AppRouterDelegate extends GetDelegate {
  @override
  Widget build(BuildContext context) {
    return Navigator(
      onPopPage: (route, result) => route.didPop(result),
      pages: currentConfiguration != null
          ? [currentConfiguration!.currentPage!]
          : [GetNavConfig.fromRoute('main')!.currentPage!],
    );
  }
}

And on different screens I go deeper and deeper. And it works the way I need it. But when I click back, I don’t move back through the history, but go back to the beginning

context.go('/main')

context.go('/main/my-friends')
context.go('/main/my-friends/${friendsList[index].id}')
context.go('/main/my-friends/${userId}/friends')
context.go('/main/my-friends/${friendsList[index].id}')

How do I make it so that when we click back, we return to the previous page, and not to the initial one?

back buttons have this code

Navigator.pop(context);

At first I tried to do it through a regular Navigator, then through Navigator 2.0. But it didn’t work. Then I found this go router and I liked it, but I can’t solve the last problem

2

Answers


  1. Use context.push(‘routeName’) instead of context.go(‘routeName’). That should resolve the issue.

    Login or Signup to reply.
  2. Have you tried using the go_router pop extension instead of Navigator.pop(context)?

    import 'package:go_router/go_router.dart';
    
    context.pop();
    

    Link to a page explaining the difference between push and go :
    Go vs Push

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search