Repository: flutter
Issue: [go_router] Routes, Subroute and popping not working properly for deeplinks
Labels: package,has reproducible steps,P2,p: go_router,team-go_router,triaged-go_router,found in release: 3.22,found in release: 3.24

### What package does this bug report belong to?

go_router

### What target platforms are you seeing this bug on?

Android, iOS

### Have you already upgraded your packages?

Yes

### Dependency versions

<details><summary>pubspec.lock</summary>

```lock
# Generated by pub
# See https://dart.dev/tools/pub/glossary#lockfile
packages:
  async:
    dependency: transitive
    description:
      name: async
      sha256: "947bfcf187f74dbc5e146c9eb9c0f10c9f8b30743e341481c1e2ed3ecc18c20c"
      url: "https://pub.dev"
    source: hosted
    version: "2.11.0"
  boolean_selector:
    dependency: transitive
    description:
      name: boolean_selector
      sha256: "6cfb5af12253eaf2b368f07bacc5a80d1301a071c73360d746b7f2e32d762c66"
      url: "https://pub.dev"
    source: hosted
    version: "2.1.1"
  characters:
    dependency: transitive
    description:
      name: characters
      sha256: "04a925763edad70e8443c99234dc3328f442e811f1d8fd1a72f1c8ad0f69a605"
      url: "https://pub.dev"
    source: hosted
    version: "1.3.0"
  clock:
    dependency: transitive
    description:
      name: clock
      sha256: cb6d7f03e1de671e34607e909a7213e31d7752be4fb66a86d29fe1eb14bfb5cf
      url: "https://pub.dev"
    source: hosted
    version: "1.1.1"
  collection:
    dependency: transitive
    description:
      name: collection
      sha256: ee67cb0715911d28db6bf4af1026078bd6f0128b07a5f66fb2ed94ec6783c09a
      url: "https://pub.dev"
    source: hosted
    version: "1.18.0"
  cupertino_icons:
    dependency: "direct main"
    description:
      name: cupertino_icons
      sha256: ba631d1c7f7bef6b729a622b7b752645a2d076dba9976925b8f25725a30e1ee6
      url: "https://pub.dev"
    source: hosted
    version: "1.0.8"
  fake_async:
    dependency: transitive
    description:
      name: fake_async
      sha256: "511392330127add0b769b75a987850d136345d9227c6b94c96a04cf4a391bf78"
      url: "https://pub.dev"
    source: hosted
    version: "1.3.1"
  flutter:
    dependency: "direct main"
    description: flutter
    source: sdk
    version: "0.0.0"
  flutter_lints:
    dependency: "direct dev"
    description:
      name: flutter_lints
      sha256: a25a15ebbdfc33ab1cd26c63a6ee519df92338a9c10f122adda92938253bef04
      url: "https://pub.dev"
    source: hosted
    version: "2.0.3"
  flutter_test:
    dependency: "direct dev"
    description: flutter
    source: sdk
    version: "0.0.0"
  flutter_web_plugins:
    dependency: transitive
    description: flutter
    source: sdk
    version: "0.0.0"
  go_router:
    dependency: "direct main"
    description:
      name: go_router
      sha256: "39dd52168d6c59984454183148dc3a5776960c61083adfc708cc79a7b3ce1ba8"
      url: "https://pub.dev"
    source: hosted
    version: "14.2.1"
  leak_tracker:
    dependency: transitive
    description:
      name: leak_tracker
      sha256: "7f0df31977cb2c0b88585095d168e689669a2cc9b97c309665e3386f3e9d341a"
      url: "https://pub.dev"
    source: hosted
    version: "10.0.4"
  leak_tracker_flutter_testing:
    dependency: transitive
    description:
      name: leak_tracker_flutter_testing
      sha256: "06e98f569d004c1315b991ded39924b21af84cf14cc94791b8aea337d25b57f8"
      url: "https://pub.dev"
    source: hosted
    version: "3.0.3"
  leak_tracker_testing:
    dependency: transitive
    description:
      name: leak_tracker_testing
      sha256: "6ba465d5d76e67ddf503e1161d1f4a6bc42306f9d66ca1e8f079a47290fb06d3"
      url: "https://pub.dev"
    source: hosted
    version: "3.0.1"
  lints:
    dependency: transitive
    description:
      name: lints
      sha256: "0a217c6c989d21039f1498c3ed9f3ed71b354e69873f13a8dfc3c9fe76f1b452"
      url: "https://pub.dev"
    source: hosted
    version: "2.1.1"
  logging:
    dependency: transitive
    description:
      name: logging
      sha256: "623a88c9594aa774443aa3eb2d41807a48486b5613e67599fb4c41c0ad47c340"
      url: "https://pub.dev"
    source: hosted
    version: "1.2.0"
  matcher:
    dependency: transitive
    description:
      name: matcher
      sha256: d2323aa2060500f906aa31a895b4030b6da3ebdcc5619d14ce1aada65cd161cb
      url: "https://pub.dev"
    source: hosted
    version: "0.12.16+1"
  material_color_utilities:
    dependency: transitive
    description:
      name: material_color_utilities
      sha256: "0e0a020085b65b6083975e499759762399b4475f766c21668c4ecca34ea74e5a"
      url: "https://pub.dev"
    source: hosted
    version: "0.8.0"
  meta:
    dependency: transitive
    description:
      name: meta
      sha256: "7687075e408b093f36e6bbf6c91878cc0d4cd10f409506f7bc996f68220b9136"
      url: "https://pub.dev"
    source: hosted
    version: "1.12.0"
  path:
    dependency: transitive
    description:
      name: path
      sha256: "087ce49c3f0dc39180befefc60fdb4acd8f8620e5682fe2476afd0b3688bb4af"
      url: "https://pub.dev"
    source: hosted
    version: "1.9.0"
  sky_engine:
    dependency: transitive
    description: flutter
    source: sdk
    version: "0.0.99"
  source_span:
    dependency: transitive
    description:
      name: source_span
      sha256: "53e943d4206a5e30df338fd4c6e7a077e02254531b138a15aec3bd143c1a8b3c"
      url: "https://pub.dev"
    source: hosted
    version: "1.10.0"
  stack_trace:
    dependency: transitive
    description:
      name: stack_trace
      sha256: "73713990125a6d93122541237550ee3352a2d84baad52d375a4cad2eb9b7ce0b"
      url: "https://pub.dev"
    source: hosted
    version: "1.11.1"
  stream_channel:
    dependency: transitive
    description:
      name: stream_channel
      sha256: ba2aa5d8cc609d96bbb2899c28934f9e1af5cddbd60a827822ea467161eb54e7
      url: "https://pub.dev"
    source: hosted
    version: "2.1.2"
  string_scanner:
    dependency: transitive
    description:
      name: string_scanner
      sha256: "556692adab6cfa87322a115640c11f13cb77b3f076ddcc5d6ae3c20242bedcde"
      url: "https://pub.dev"
    source: hosted
    version: "1.2.0"
  term_glyph:
    dependency: transitive
    description:
      name: term_glyph
      sha256: a29248a84fbb7c79282b40b8c72a1209db169a2e0542bce341da992fe1bc7e84
      url: "https://pub.dev"
    source: hosted
    version: "1.2.1"
  test_api:
    dependency: transitive
    description:
      name: test_api
      sha256: "9955ae474176f7ac8ee4e989dadfb411a58c30415bcfb648fa04b2b8a03afa7f"
      url: "https://pub.dev"
    source: hosted
    version: "0.7.0"
  vector_math:
    dependency: transitive
    description:
      name: vector_math
      sha256: "80b3257d1492ce4d091729e3a67a60407d227c27241d6927be0130c98e741803"
      url: "https://pub.dev"
    source: hosted
    version: "2.1.4"
  vm_service:
    dependency: transitive
    description:
      name: vm_service
      sha256: "3923c89304b715fb1eb6423f017651664a03bf5f4b29983627c4da791f74a4ec"
      url: "https://pub.dev"
    source: hosted
    version: "14.2.1"
sdks:
  dart: ">=3.3.0 <4.0.0"
  flutter: ">=3.18.0-18.0.pre.54"

```

</details>


### Steps to reproduce

1. Add the code of `main.dart` provided below and add `go_router: ^14.2.1` in `pubspec.yaml` and run the project.
2. On the DashboardPage, click on the button `GO TO LOGIN PAGE`.
3. After the LoginPage opens, click on the button `GO TO PIN PAGE`.
4. After the PinPage opens, click on the button `GO TO HOME PAGE`.
5. After the HomePage opens, click on the button `GO TO END PAGE`.
6. After the EndPage opens click on the button `GO TO SUBROUTE PAGE`.
7. Finally opens the SubRoutePage.

This app was built to display a simple flow for most app where it starts with Login -> Pin -> Home -> End -> Subroutes
If you followed the above steps then in the Debug Console, this should get logged by GoRouter.
<details><summary>Debug Console</summary>

```console
[GoRouter] Full paths for routes:
           └─/ (DashboardPage)
             ├─/login (LoginPage)
             ├─/pin (PinPage)
             ├─/home (HomePage)
             └─/end (EndPage)
               └─ (ShellRoute)
                 └─/end/subroute (SubRoutePage)
           known full paths for route names:
             /login => /login
             /pin => /pin
             /home => /home
             /end => /end
             /subroute => /end/subroute
[GoRouter] setting initial location null
[GoRouter] Using MaterialApp configuration
[GoRouter] getting location for name: "/login"
[GoRouter] pushing /login
[GoRouter] getting location for name: "/pin"
[GoRouter] pushing /pin
[GoRouter] getting location for name: "/home"
[GoRouter] pushing /home
[GoRouter] getting location for name: "/end"
[GoRouter] pushing /end
[GoRouter] getting location for name: "/subroute"
[GoRouter] pushing /end/subroute
[GoRouter] Using MaterialApp configuration

```
</details>

Now if I press the back button (I am in the SubRoutePage currently), then this is printed in the console `[GoRouter] popping /`.
If I keep pressing the back button on every screen then the same thing is logged everytime for 5 times and I get this printed in the debug console until I get back to the DashboardPage.

<details><summary>Debug Console</summary>

```console
[GoRouter] popping /
[GoRouter] popping /
[GoRouter] popping /
[GoRouter] popping /
[GoRouter] popping /

```
</details>

### Expected results

1. **Logging issue with normal routes ->** If I am using router.pushNamed and went from `DashboardPage` till `EndPage` then it should log it as `[GoRouter] pushing /login/pin/home/end` as all of the routes have been stacked because I used pushNamed but instead the last routes are logged as `[GoRouter] pushing /end` if I follow the same process.


2.  **Logging issue with subroutes routes ->** If I am using router.pushNamed and went from `EndPage` to `SubRoutePage` then it should log it as `[GoRouter] pushing /end/subroute` which is correctly logged as I have created a subroute for the same provided in the code below in `main.dart` but if I press the back button on SubRoutePage then the page goes back to the correct screen which is the EndPage but in the console we get `[GoRouter] popping /`, it should have been `[GoRouter] popping /end`. The wrong logging wouldn't be a problem as I still went to the correct screen on pressing the back button but when we receive a deeplink for the SubRoutePage from notification and press the back button in SubRoutePage, it takes me back directly to the DashboardPage as DashboardPage is set to `/` and it does the same whereas it should have redirected me to EndPage since thats what the subroute mentioned `/end/subroute` so it should have logged it as `/end` which would have led to the correct screen as `/subroute` would have been popped from '/end/subroute` leading to `/end` route.

Expected Result -> Correct logging of routes and the subroutes to be fixed so that when I use router.pop() on the subroute `/end/subroute` screen that has been opened by a subroute, it pops to the previous route which is '/end' and print the same in the debug console.

### Actual results

1. **Logging issue with normal routes ->** If I am using router.pushNamed and went from `DashboardPage` till `EndPage` then it is logged as `[GoRouter] pushing /end`

2.  **Logging issue with subroutes routes ->** If I press the back button on `SubRoutePage` when I went from `EndPage` to `SubRoutePage` then it is logging as `[GoRouter] popping /`, it should have been `[GoRouter] popping /end`. The wrong logging wouldn't be a problem as I still went to the correct screen on pressing the back button but when we recieve the deeplink for the SubRoutePage from notification and press the back button in SubRoutePage, it takes me back directly to the DashboardPage whereas it should have redirected me to EndPage since thats whats mentioned in the subroute. 

### Code sample

<details open><summary>Code sample</summary>

```dart
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp.router(
      // routerConfig: router,
      routeInformationParser: router.routeInformationParser,
      routerDelegate: router.routerDelegate,
      routeInformationProvider: router.routeInformationProvider,
    );
  }
}

class DashboardPage extends StatelessWidget {
  const DashboardPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: const Text('DashboardPage'),
      ),
      body: Center(
        child: Center(
          child: ElevatedButton(
            child: const Text('GO TO LOGIN PAGE'),
            onPressed: () {
              router.pushNamed('/login');
            },
          ),
        ),
      ),
    );
  }
}

class LoginPage extends StatelessWidget {
  const LoginPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: const Text('LoginPage'),
        leading: GestureDetector(
            onTap: () {
              router.pop();
            },
            child: const Icon(Icons.arrow_back)),
      ),
      body: Center(
          child: ElevatedButton(
        child: const Text('GO TO PIN PAGE'),
        onPressed: () {
          router.pushNamed('/pin');
        },
      )),
    );
  }
}

class PinPage extends StatelessWidget {
  const PinPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: const Text('PinPage'),
        leading: GestureDetector(
            onTap: () {
              router.pop();
            },
            child: const Icon(Icons.arrow_back)),
      ),
      body: Center(
          child: ElevatedButton(
        child: const Text('GO TO HOME PAGE'),
        onPressed: () {
          router.pushNamed('/home');
        },
      )),
    );
  }
}

class HomePage extends StatelessWidget {
  const HomePage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: const Text('HomePage'),
        leading: GestureDetector(
            onTap: () {
              router.pop();
            },
            child: const Icon(Icons.arrow_back)),
      ),
      body: Center(
          child: ElevatedButton(
        child: const Text('GO TO END PAGE'),
        onPressed: () {
          router.pushNamed('/end');
        },
      )),
    );
  }
}

class EndPage extends StatelessWidget {
  const EndPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: const Text('EndPage'),
        leading: GestureDetector(
            onTap: () {
              router.pop();
            },
            child: const Icon(Icons.arrow_back)),
      ),
      body: Center(
          child: ElevatedButton(
        child: const Text('GO TO SUBROUTE PAGE'),
        onPressed: () {
          router.pushNamed('/subroute');
        },
      )),
    );
  }
}

final GoRouter router = GoRouter(
  debugLogDiagnostics: true,
  routes: <RouteBase>[
    GoRoute(
      path: '/',
      builder: (BuildContext context, GoRouterState state) {
        return const DashboardPage();
      },
      routes: <RouteBase>[
        GoRoute(
          path: 'login',
          name: '/login',
          builder: (BuildContext context, GoRouterState state) {
            return const LoginPage();
          },
        ),
        GoRoute(
          path: 'pin',
          name: '/pin',
          builder: (BuildContext context, GoRouterState state) {
            return const PinPage();
          },
        ),
        GoRoute(
          path: 'home',
          name: '/home',
          builder: (BuildContext context, GoRouterState state) {
            return const HomePage();
          },
        ),
        GoRoute(
          path: 'end',
          name: '/end',
          builder: (BuildContext context, GoRouterState state) {
            return const EndPage();
          },
          routes: [
            ShellRoute(
              builder: (context, state, child) {
                return child;
              },
              routes: [
                subroutePush,
              ],
            ),
          ],
        ),
      ],
    ),
  ],
);

final subroutePush = GoRoute(
  path: 'subroute',
  name: '/subroute',
  builder: (BuildContext context, GoRouterState state) {
    return const EndPage();
  },
);

```

</details>


### Screenshots or Videos

<details open>
<summary>Screenshots / Video demonstration</summary>

[Upload media here]

</details>


### Logs

<details open><summary>Logs</summary>

```console
Restarted application in 687ms.
[GoRouter] Full paths for routes:
           └─/ (DashboardPage)
             ├─/login (LoginPage)
             ├─/pin (PinPage)
             ├─/home (HomePage)
             └─/end (EndPage)
               └─ (ShellRoute)
                 └─/end/subroute (SubRoutePage)
           known full paths for route names:
             /login => /login
             /pin => /pin
             /home => /home
             /end => /end
             /subroute => /end/subroute
[GoRouter] setting initial location null
[GoRouter] Using MaterialApp configuration
D/EGL_emulation(30325): app_time_stats: avg=229195.66ms min=229195.66ms max=229195.66ms count=1
[GoRouter] getting location for name: "/login"
[GoRouter] pushing /login
W/WindowOnBackDispatcher(30325): OnBackInvokedCallback is not enabled for the application.
W/WindowOnBackDispatcher(30325): Set 'android:enableOnBackInvokedCallback="true"' in the application manifest.
D/EGL_emulation(30325): app_time_stats: avg=9750.58ms min=9750.58ms max=9750.58ms count=1
[GoRouter] getting location for name: "/pin"
[GoRouter] pushing /pin
W/WindowOnBackDispatcher(30325): OnBackInvokedCallback is not enabled for the application.
W/WindowOnBackDispatcher(30325): Set 'android:enableOnBackInvokedCallback="true"' in the application manifest.
D/EGL_emulation(30325): app_time_stats: avg=106.97ms min=1.09ms max=1219.23ms count=12
[GoRouter] getting location for name: "/home"
[GoRouter] pushing /home
W/WindowOnBackDispatcher(30325): OnBackInvokedCallback is not enabled for the application.
W/WindowOnBackDispatcher(30325): Set 'android:enableOnBackInvokedCallback="true"' in the application manifest.
D/EGL_emulation(30325): app_time_stats: avg=25.04ms min=1.51ms max=496.41ms count=32
[GoRouter] getting location for name: "/end"
[GoRouter] pushing /end
W/WindowOnBackDispatcher(30325): OnBackInvokedCallback is not enabled for the application.
W/WindowOnBackDispatcher(30325): Set 'android:enableOnBackInvokedCallback="true"' in the application manifest.
[GoRouter] getting location for name: "/subroute"
[GoRouter] pushing /end/subroute
[GoRouter] Using MaterialApp configuration
W/WindowOnBackDispatcher(30325): OnBackInvokedCallback is not enabled for the application.
W/WindowOnBackDispatcher(30325): Set 'android:enableOnBackInvokedCallback="true"' in the application manifest.
D/EGL_emulation(30325): app_time_stats: avg=54.06ms min=1.27ms max=577.00ms count=25
[GoRouter] popping /
W/WindowOnBackDispatcher(30325): OnBackInvokedCallback is not enabled for the application.
W/WindowOnBackDispatcher(30325): Set 'android:enableOnBackInvokedCallback="true"' in the application manifest.
D/EGL_emulation(30325): app_time_stats: avg=19111.38ms min=13.41ms max=362816.81ms count=19
[GoRouter] popping /
W/WindowOnBackDispatcher(30325): OnBackInvokedCallback is not enabled for the application.
W/WindowOnBackDispatcher(30325): Set 'android:enableOnBackInvokedCallback="true"' in the application manifest.
D/EGL_emulation(30325): app_time_stats: avg=26.70ms min=1.11ms max=546.47ms count=28
[GoRouter] popping /
W/WindowOnBackDispatcher(30325): OnBackInvokedCallback is not enabled for the application.
W/WindowOnBackDispatcher(30325): Set 'android:enableOnBackInvokedCallback="true"' in the application manifest.
D/EGL_emulation(30325): app_time_stats: avg=38.46ms min=12.88ms max=581.29ms count=26
[GoRouter] popping /
W/WindowOnBackDispatcher(30325): OnBackInvokedCallback is not enabled for the application.
W/WindowOnBackDispatcher(30325): Set 'android:enableOnBackInvokedCallback="true"' in the application manifest.
[GoRouter] popping /
D/EGL_emulation(30325): app_time_stats: avg=38.46ms min=8.04ms max=310.97ms count=26

```

</details>


### Flutter Doctor output

<details open><summary>Doctor output</summary>

```console
[✓] Flutter (Channel stable, 3.22.0, on macOS 14.1.2 23B92 darwin-arm64, locale en-IN)
    • Flutter version 3.22.0 on channel stable at /Users/marufhassan/flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision 5dcb86f68f (3 months ago), 2024-05-09 07:39:20 -0500
    • Engine revision f6344b75dc
    • Dart version 3.4.0
    • DevTools version 2.34.3

[✓] Android toolchain - develop for Android devices (Android SDK version 34.0.0)
    • Android SDK at /Users/marufhassan/Library/Android/sdk
    • Platform android-34, build-tools 34.0.0
    • ANDROID_HOME = /Users/marufhassan/Library/Android/sdk
    • Java binary at: /Applications/Android Studio.app/Contents/jbr/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 17.0.6+0-17.0.6b829.9-10027231)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 15.3)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Build 15E204a
    • CocoaPods version 1.15.2

[✓] Chrome - develop for the web
    • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] Android Studio (version 2022.3)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 17.0.6+0-17.0.6b829.9-10027231)

[✓] VS Code (version 1.91.1)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.92.0

[✓] Connected device (4 available)
    • sdk gphone64 arm64 (mobile)     • emulator-5554         • android-arm64  • Android 15 (API 35)
      (emulator)
    • macOS (desktop)                 • macos                 • darwin-arm64   • macOS 14.1.2 23B92
      darwin-arm64
    • Mac Designed for iPad (desktop) • mac-designed-for-ipad • darwin         • macOS 14.1.2 23B92
      darwin-arm64
    • Chrome (web)                    • chrome                • web-javascript • Google Chrome
      127.0.6533.72

[✓] Network resources
    • All expected network resources are available.

• No issues found!
```

</details>