Skip to content

[go_router] Root-navigator redirect page is omitted when restoring a StatefulShellRoute branch #194209

Open
flutter/packages
#13735

Description

@AyatAliev

What package does this bug report belong to?

go_router

Summary

When a StatefulShellRoute branch redirects to a child route displayed on the root navigator, switching away and restoring the branch with goBranch() can omit the redirect page. The cached branch RouteMatchList contains the branch matches but still has the URI of the root-navigator child that was removed from those matches.

Steps to reproduce

  1. Configure two branches, /a and /b, in StatefulShellRoute.indexedStack.
  2. Redirect /b to /b/welcome. Configure welcome as a child of /b with parentNavigatorKey set to the root navigator key. The redirect remains required on every entry.
  3. Start at /a, then select branch B using navigationShell.goBranch(1). The welcome page appears.
  4. On the welcome page, cancel by calling context.go('/a').
  5. Select branch B again using navigationShell.goBranch(1) with the default initialLocation: false.

Expected results

The welcome page appears again because the redirect condition has not changed. The restored branch cache should have a URI and path parameters consistent with its remaining route matches.

Actual results

On the second entry, the branch page is displayed without the welcome page. The cached list excludes the root-navigator child, but its URI still points to /b/welcome. The restore parser can therefore retain the cached list instead of the newly matched redirect destination.

Code sample

Save the following as test/branch_restore_test.dart in a Flutter project with go_router and flutter_test dependencies, then run flutter test test/branch_restore_test.dart.

This sample is supplied for upstream reproduction. It has not been executed against upstream 18.0.2 in this report; see the verification scope below.

import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:go_router/go_router.dart';

void main() {
  testWidgets('root redirect page returns after branch restoration', (tester) async {
    final rootKey = GlobalKey<NavigatorState>();
    final router = GoRouter(
      navigatorKey: rootKey,
      initialLocation: '/a',
      routes: [
        StatefulShellRoute.indexedStack(
          builder: (context, state, shell) => Scaffold(
            body: shell,
            bottomNavigationBar: Row(
              children: [
                TextButton(
                  onPressed: () => shell.goBranch(0),
                  child: const Text('Branch A'),
                ),
                TextButton(
                  onPressed: () => shell.goBranch(1),
                  child: const Text('Branch B'),
                ),
              ],
            ),
          ),
          branches: [
            StatefulShellBranch(
              routes: [
                GoRoute(
                  path: '/a',
                  builder: (context, state) => const Center(child: Text('Page A')),
                ),
              ],
            ),
            StatefulShellBranch(
              routes: [
                GoRoute(
                  path: '/b',
                  redirect: (context, state) =>
                      state.uri.path == '/b/welcome' ? null : '/b/welcome',
                  builder: (context, state) => const Center(child: Text('Page B')),
                  routes: [
                    GoRoute(
                      path: 'welcome',
                      parentNavigatorKey: rootKey,
                      builder: (context, state) => Scaffold(
                        body: Column(
                          children: [
                            const Text('Welcome'),
                            TextButton(
                              onPressed: () => context.go('/a'),
                              child: const Text('Cancel'),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ],
        ),
      ],
    );
    addTearDown(router.dispose);
    await tester.pumpWidget(MaterialApp.router(routerConfig: router));
    await tester.pumpAndSettle();

    await tester.tap(find.text('Branch B'));
    await tester.pumpAndSettle();
    expect(find.text('Welcome'), findsOneWidget);

    await tester.tap(find.text('Cancel'));
    await tester.pumpAndSettle();
    expect(find.text('Page A'), findsOneWidget);

    await tester.tap(find.text('Branch B'));
    await tester.pumpAndSettle();
    expect(find.text('Welcome'), findsOneWidget);
    expect(router.routerDelegate.currentConfiguration.uri.path, '/b/welcome');
    expect(tester.takeException(), isNull);
  });
}

Source analysis

The relevant upstream code was inspected at flutter/packages commit 3b733d27c63cf7b6012e99afacd267d3a24de5a3, whose go_router/pubspec.yaml declares version 18.0.2.

  1. _scopedMatchList() uses matchList.copyWith(matches: _scopeMatches(matchList.matches)). _scopeMatches() discards matches following the current shell, including the root-navigator child in this scenario.
  2. RouteMatchList.copyWith() retains the previous uri and pathParameters when they are not supplied. The resulting list therefore has inconsistent matches and location metadata.
  3. goBranch() restores this cached list.
  4. In NavigatingType.restore, when the cached and newly matched URIs are equal, the parser returns the cached list. Here both URIs are /b/welcome, but the cached list lacks the welcome match.

Candidate fix and regression coverage

RouteMatchList.remove() already updates the URI path and removes obsolete path parameters when the remaining full path changes. Scoping the branch by removing excluded matches through this API, rather than replacing only matches, is a candidate fix.

A public fork PR contains this approach and regression tests: denihero/packages#1. That PR targets a fork, was closed without merge, and does not constitute an upstream fix. Its test suite includes repeated cancellation/re-entry, root-popup URI cleanup, branch path parameters, and preservation of imperative/declarative branch stacks. Any test results reported there apply to that fork, not to upstream 18.0.2.

Verification scope and environment

  • The original behavior was reported in the fork scenario linked above.
  • Current upstream source inspection confirms that the same scoping/copy/restore path remains at the pinned commit.
  • Upstream runtime reproduction and the sample test above have not been run for this report. No claim of a test failure or successful fix on upstream 18.0.2 is made.
  • Platform-specific confirmation, a dependency lockfile, and Flutter Doctor output for an upstream reproduction are not yet available.

Related report

#158238 also reports a branch restoration/navigation mismatch, but its sample uses pop() followed by go() and does not use a root-navigator child redirect. This report isolates the inconsistent cached URI produced by branch scoping.

Activity

  1. AyatAliev commented on Oct 12, 2026

    @AyatAliev
    Author

    Proposed fix: flutter/packages#13735. It continues flutter/packages#13202, which was closed after I accidentally deleted my fork; the review discussion is there.

  2. suryaKommana2662 commented on Oct 13, 2026

    @suryaKommana2662
    Contributor

    @AyatAliev I was able to reproduce the reported behavior locally using the provided test with flutter test test/branch_restore_test.dart.

    go_router: ^18.0.2

    The test failed with the following output:

    suryakommana@SuryaKommanas-MacBook-Pro counter % flutter test test/branch_restore_test.dart
    00:04 +0: root redirect page returns after branch restoration                                                                                                         
    ══╡ EXCEPTION CAUGHT BY FLUTTER TEST FRAMEWORK ╞════════════════════════════════════════════════════
    The following TestFailure was thrown running a test:
    Expected: exactly one matching candidate
      Actual: _TextWidgetFinder:<Found 0 widgets with text "Welcome": []>
       Which: means none were found but one was expected
    
    When the exception was thrown, this was the stack:
    #4      main.<anonymous closure> (file:///Users/suryakommana/StudioProjects/counter/test/branch_restore_test.dart:82:5)
    <asynchronous suspension>
    #5      testWidgets.<anonymous closure>.<anonymous closure> (package:flutter_test/src/widget_tester.dart:192:15)
    <asynchronous suspension>
    #6      TestWidgetsFlutterBinding._runTestBody (package:flutter_test/src/binding.dart:1953:5)
    <asynchronous suspension>
    <asynchronous suspension>
    (elided one frame from package:stack_trace)
    
    This was caught by the test expectation on the following line:
      file:///Users/suryakommana/StudioProjects/counter/test/branch_restore_test.dart line 82
    The test description was:
      root redirect page returns after branch restoration
    ════════════════════════════════════════════════════════════════════════════════════════════════════
    00:04 +0 -1: root redirect page returns after branch restoration [E]                                                                                                  
      Test failed. See exception logs above.
      The test description was: root redirect page returns after branch restoration
      
    
    To run this test again: /Users/suryakommana/develop/flutter/bin/cache/dart-sdk/bin/dart test /Users/suryakommana/StudioProjects/counter/test/branch_restore_test.dart -p vm --plain-name 'root redirect page returns after branch restoration'
    00:04 +0 -1: Some tests failed.  

    I also noticed the proposed fix in flutter/packages#13202. routing this to the team-ecosystem for further investigation

    Flutter Doctor Output

    [✓] Flutter (Channel stable, 3.47.7, on macOS 27.0 26A428 darwin-arm64, locale en-IN) [268ms]
        • Flutter version 3.47.7 on channel stable at /Users/suryakommana/develop/flutter
        • Upstream repository https://github.com/flutter/flutter.git
        • Framework revision abaf9c5237 (4 days ago), 2026-10-08 09:51:21 -0700
        • Engine revision deb287481e
        • Dart version 3.13.5
        • DevTools version 2.60.0
        • Feature flags: enable-web, enable-linux-desktop, enable-macos-desktop, enable-windows-desktop, enable-android, enable-ios, cli-animations, enable-native-assets,
          enable-record-use, enable-swift-package-manager, omit-legacy-version-file, enable-lldb-debugging, enable-uiscene-migration
    
    [✓] Android toolchain - develop for Android devices (Android SDK version 36.0.0) [1,818ms]
        • Android SDK at /Users/suryakommana/Library/Android/sdk
        • Emulator version 37.1.11.0 (build_id 15917651) (CL:N/A)
        • Platform android-37.0, build-tools 36.0.0
        • Java binary at: /Applications/Android Studio.app/Contents/jbr/Contents/Home/bin/java
          This is the JDK bundled with the latest Android Studio installation on this machine.
          To manually set the JDK path, use: `flutter config --jdk-dir="path/to/jdk"`.
        • Java version OpenJDK Runtime Environment (build 25.0.2+-15348964-b329.117)
        • All Android licenses accepted.
    
    [✓] Xcode - develop for iOS and macOS (Xcode 27.0) [1,448ms]
        • Xcode at /Applications/Xcode.app/Contents/Developer
        • Build 27A266a
        • CocoaPods version 1.17.0
    
    [✓] Chrome - develop for the web [3ms]
        • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome
    
    [✓] Connected device (2 available) [9.3s]
        • macOS (desktop) • macos  • darwin-arm64   • macOS 27.0 26A428 darwin-arm64
        • Chrome (web)    • chrome • web-javascript • Google Chrome 155.0.8059.40
    
    [✓] Network resources [715ms]
        • All expected network resources are available.
    
    • No issues found!
  3. added
    packageflutter/packages repository. See also p: labels.
    has reproducible stepsThe issue has been confirmed reproducible and is ready to work on
    a: tests"flutter test", flutter_test, or one of our tests
    and removed
    in triagePresently being triaged by the triage team
    on Oct 13, 2026
  4. added
    P2Important issues not at the top of the work list
    on Oct 20, 2026
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

    P2Important issues not at the top of the work lista: tests"flutter test", flutter_test, or one of our testshas reproducible stepsThe issue has been confirmed reproducible and is ready to work onp: go_routerThe go_router packagepackageflutter/packages repository. See also p: labels.team-ecosystemOwned by Ecosystem teamtriaged-ecosystemTriaged by Ecosystem team

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions