Skip to content

[go_router] choose in redirect method if push or go #114131

Open

Description

@dzziwny

I would like to choose in redirect method if i want to clear a navigation history (as it is in context.go), even if i started navigation with context.push.

Use case

On application start i have a few configuration pages that user setup once, and finally ends up in dashboard page.
Possible navigation flows (depend on what user already setup, and what skipped in the past):

'/' -> '/dashboard'
'/' -> '/language' -> '/dashboard'
'/' -> '/welcome'/ -> '/dashboard'
'/' -> '/welcome'/ -> '/language' -> '/dashboard'

In language page i want to have a back button in appbar and be able to pop page. When i ends up in dashboard i would like to have a clear navigation history.

Proposal

  1. There could be a Redirection class, with clearHistory parameter (false by default).
GoRoute(
      path: '/language,
      builder: (_, __) => const LanguagePage(),
      redirect: (_, __) {
          final skipToDashboard = ...;
          if (skipToDashboard) {
              return Redirection('/dashboard', clearHistory: true);
          }
          
          return null;
      }
    ),
  1. Add clearHistory method to GoRouter class.

Activity

  1. added
    in triage
    on Oct 27, 2022
  2. exaby73 commented on Oct 27, 2022

    @exaby73
    Member

    Hello @dzziwny. Thank you for filing this request. Labelling the issue for visibility and insights from the team

  3. added
    c: new feature
    package
    c: proposal
    p: go_router
    and removed
    in triage
    on Oct 27, 2022
  4. added
    P3
    on Oct 27, 2022
  5. chunhtai commented on Oct 27, 2022

    @chunhtai
    Contributor

    you can have a top level route and use go to clear the history.

  6. added
    waiting for response
    on Oct 27, 2022
  7. dzziwny commented on Oct 28, 2022

    @dzziwny
    Author

    You mean, the top route over setup pages, like for ex. /setup/language? But if i go from /setup/welcome to /setup/language i need to use push anyway, right? The problem is that i don't want to decide from any setup page wether to use push or go - I am doing it now and have a separated service that resolves the next step and decide which method to use - it works but looks ugly and redirect lost any sense.

  8. removed
    waiting for response
    on Oct 28, 2022
  9. hunterwilhelm commented on Nov 29, 2022

    @hunterwilhelm

    Sometimes redirect does a popUntil. Demonstrated in #116164.

    Could we add a way to choose between push, go, and popUntil too?

  10. 37 remaining items

  11. Sukarma33 commented on Dec 12, 2024

    @Sukarma33

    I have a similar request, that would require a redirect action to perform push instead of go.

    I need to have routes under /account "guarded" with login check - so if user is not logged in - a sign in page shows up in root navigator (so over the StackRoute and BottomNavigationBar). However I also need the /user/login to be regular route that can be called from anywhere and would behave the same.

    Below is a code sample that parially works. By partially I mean that redirect works - it opens the /user/login route, it covers the screen, but there is no "back" arrow and the "back" action just closes the app.
    main.dart

    import 'package:flutter/material.dart';
    import 'package:go_router/go_router.dart';
    
    void main() => runApp(const MyApp());
    
    // #region Router
    final _rootNavigatorKey = GlobalKey<NavigatorState>(debugLabel: 'root');
    final _shellNavigatorKey = GlobalKey<NavigatorState>(debugLabel: 'shell');
    
    final _router = GoRouter(
      navigatorKey: _rootNavigatorKey,
      initialLocation: '/',
      redirect: (context, state) {
        if (state.location == "/account") return "/user/login";
        return null;
      },
      routes: [
        ShellRoute(
          navigatorKey: _shellNavigatorKey,
          builder: (context, state, child) {
            return ScaffoldWithNavBar(child: child);
          },
          routes: [
            GoRoute(
              path: "/",
              builder: (_, __) => const HomePage(),
            ),
            GoRoute(
              path: "/account",
              // redirect: (_, __) => "/user/login",
    
              pageBuilder: (BuildContext context, GoRouterState state) => MaterialPage<void>(
                key: state.pageKey,
                child: const AccountPage(),
              ),
            ),
          ],
        ),
        // I want this route to cover the entire screen (including bottom nav) - this works
        // However, I want to be able to get back from the redirect
        // So if user decides to NOT sign-in - he can go back to previous route
        // I assume that currently go_router uses .go, while I need push on redirect
        GoRoute(
          parentNavigatorKey: _rootNavigatorKey,
          path: "/user/login",
          builder: (_, __) => const LoginPage(),
        ),
      ],
    );
    // #endregion
    
    class MyApp extends StatelessWidget {
      const MyApp({super.key});
    
      // This widget is the root of your application.
      @override
      Widget build(BuildContext context) {
        return MaterialApp.router(
          title: 'Go Router Demo',
          theme: ThemeData(
            primarySwatch: Colors.blue,
          ),
          routerConfig: _router,
        );
      }
    }
    
    class ScaffoldWithNavBar extends StatelessWidget {
      final Widget child;
    
      const ScaffoldWithNavBar({
        required this.child,
        super.key,
      });
    
      static int _calculateSelectedIndex(BuildContext context) {
        final location = GoRouterState.of(context).location;
        if (location.startsWith('/home')) return 0;
        if (location.startsWith('/account')) return 1;
    
        return 0;
      }
    
      void _onItemTapped(int index, BuildContext context) {
        switch (index) {
          case 0:
            GoRouter.of(context).go('/home');
            break;
          case 1:
            GoRouter.of(context).go('/account');
            break;
        }
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: child,
          bottomNavigationBar: BottomNavigationBar(
            items: const <BottomNavigationBarItem>[
              BottomNavigationBarItem(
                icon: Icon(Icons.home),
                label: 'Home',
              ),
              BottomNavigationBarItem(
                icon: Icon(Icons.person),
                label: 'Account',
              ),
            ],
            currentIndex: _calculateSelectedIndex(context),
            onTap: (int idx) => _onItemTapped(idx, context),
          ),
        );
      }
    }
    
    class HomePage extends StatelessWidget {
      const HomePage({super.key});
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(title: const Text("HomePage")),
        );
      }
    }
    
    class AccountPage extends StatelessWidget {
      const AccountPage({super.key});
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(title: const Text("AccountPage")),
        );
      }
    }
    
    class LoginPage extends StatelessWidget {
      const LoginPage({super.key});
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(title: const Text("LoginPage")),
          body: const Center(child: Text("This screen should cover the bottom nav bar, and have the 'back' arrow in AppBar.")),
        );
      }
    }
    

    I have the same issue, have you found the solution?

  12. christo-caddayn commented on Feb 13, 2025

    @christo-caddayn

    I did a workaround. I don't know wheter it suits other usecases.

    FutureOr<String?> redirect(BuildContext context, GoRouterState state) async {
    if (!isAppLatest) { // REDIRECTION CONDITION
    final p = 'my-path-to/screen';
    String data = 'sample data';

    Future.delayed(Duration(milliseconds: 100),
        () => GoRouter.of(context).go(p, extra: data)); // ADDING A FUTURE CALL WHICH WILL BE CALLED AFTER REDIRECTION
    return p;
    

    }
    }

    I know this is not the best way. Just posting here so that anyone looking for workarounds can try this.

  13. abdullahrs commented on Feb 19, 2025

    @abdullahrs

    This feature is crucial for complex deep-linking scenarios. Simply redirecting to the given location causes the loss of the existing navigation stack.

  14. chunhtai commented on Feb 19, 2025

    @chunhtai
    Contributor

    This pr should support this feature flutter/packages#8339

  15. added
    team-framework
    triaged-framework
    and removed on Jun 5, 2025
  16. omar-hanafy commented on Oct 26, 2025

    @omar-hanafy

    Status update:
    Top-level onEnter shipped in go_router 16.3.0 (PR #8339). It lets apps intercept incoming navigation, implement deep-link handling without page renders, and decide push vs go semantics before legacy redirects and route-level redirects run.

    @chunhtai, I think we might close this as completed.

  17. added
    customer: crowd
    on Dec 1, 2025
  18. added
    team-ecosystem
    triaged-ecosystem
    and removed
    team-framework
    triaged-framework
    on Aug 26, 2026
  19. curiosissimoz commented on Nov 16, 2026

    @curiosissimoz

    Status update: Top-level onEnter shipped in go_router 16.3.0 (PR #8339). It lets apps intercept incoming navigation, implement deep-link handling without page renders, and decide push vs go semantics before legacy redirects and route-level redirects run.

    @chunhtai, I think we might close this as completed.

    I don't think we can mark this as completed, since the user who opened this issue asked not for a global onEnter, but for a per-route onEnter.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    P3c: new featurec: proposalcustomer: crowdp: go_routerpackageteam-ecosystemtriaged-ecosystem

    Type

    No type

    Projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions