Repository: flutter
Issue: [go_router] `context.push` --> `context.pop` --> `context.push` causes pages to be presented twice OR pop is not removing them
Labels: package,has reproducible steps,P2,p: go_router,team-go_router,triaged-go_router,found in release: 3.24,found in release: 3.25

### Steps to reproduce

This occurs with: 
go_router version 14.2.7
Flutter 3.24.2 or 3.25.x (any version of 3.25)

If you programmatically `.push` --> `.pop` --> `.push` (a second time), then the second time you do a push of a screen, **_two_** screens are pushed onto the stack / presented to the user at the same time.

Searching through other issues Ive seen people discuss builder running twice (https://github.com/flutter/flutter/issues/153498).  However, I'm not sure that is the issue here.  I am wondering if `.pop()` isn't removing the screen from the stack, although it is popped out of view.  In this situation when you ask it to push a new one it rebuilds the original page as well to 'restore' the state of the other page that was removed from view

Im not sure about this idea, but never the less you can run the below code to see the problem first hand and see its real and systematically occurs.

Ive put in a console `debugPrint` to show which screens are going through builder and you can get a sense of that as well.

To be clean, this behavior **ONLY** occurs if you programmatically `push` then `pop` then `push` again.  If you close a screen using the back button on the top left of the screen or if you drag to close a screen (drag left to right) then the screen is properly popped and this bug won't occur.

Ive attached code below as a demonstrator model, but to reproduce the problem here are some steps


## **WORKING/PROPER OPERATION:**
1. Tap `purple` container to open `Screen B`
2. Either swipe the screen closed or tap the text "Press Here to Close me out!" to close the screen
3. Tap `blue` container to open `Screen C`
4. Either swipe the screen closed or tap the text "Press Here to Close me out!" to close the screen

## **BUGGED OPERATION**
1. Tap `purple` container to open `Screen B`
2. **Tap the house icon on the bottom navigation bar to programmatically close the screen with (`context.pop()`)**.  (Importantly, DO NOT tap on "Press here to close me", tap on the house tab bar icon which I've setup to run `context.pop`), the screen should now close (but I theorize the screen still lives in the stack somehow)
3. Tap `blue` container to open `Screen C`
4. Either swipe the screen closed or tap the text "Press Here to Close me out!" to close the screen
5. You will notice that `Screen B` is underneath `Screen C` <--- here is where you can see the bug.
6. If at this point you try to close out the underlying second screen, you will then get the app to hang/freeze

### **Notes**
In bugged operation, you can observe in the console, that when Step 3 is performed, the builder for screen B and C are both run back to back as the debugPrint `***** I AM BUILDING SCREEN B *****` and `***** I AM BUILDING SCREEN C *****` are both presented in the console

### **Extra notes:**
- If I were to use `context.go` then this bug does not occur.  However, in my implementation I may have to get to `Screen B` or `Screen C` from any number of places and I would have to expand my route list massively and almost endlessly to account from all the points at which those screen could be opened.   Using `.push` is ideal to allow my users to enter those screens at any time they like
- Ive read one suggestion about turning ScreenB/C into `const` widgets to avoid 'rebuilding' them.  Turning them into `const` is not viable since I need to feed a bunch of variables to them.  In this case for the demonstrator I put a title variable in the builder to demonstrate the concept.  Those vars come in as params or extra using context.push or from deep links url pattern

### Expected results

Two screens should not be opened

### Actual results

Two screen are opened

### Code sample

<details open><summary>Code sample</summary>

**main.dart**
```dart
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'main_router.dart';

final GlobalKey<NavigatorState> rootNavigatorKey = GlobalKey<NavigatorState>(debugLabel: 'root');

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(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      routerConfig: router,
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Column(
              children: [
                const Text("Hi i'm screen A (home screen)"),

                Container(height:20),

                GestureDetector(
                  onTap: (){
                    context.pushNamed('screenB');
                  },
                  child: Container(
                    color: Colors.purple,
                    child: const Text(
                      'Press Here to goto Screen B',
                    ),
                  ),
                ),


                Container(height:20),

                GestureDetector(
                  onTap: (){
                    context.pushNamed('screenC');
                  },
                  child: Container(
                    color: Colors.blue,
                    child: const Text(
                      'Press Here to goto Screen C',
                    ),
                  ),
                ),

              ],
            ),
          ],
        ),
      ),
    );
  }
}



class ScreenB extends StatefulWidget {
  const ScreenB({super.key, required this.title});
  final String title;

  @override
  State<ScreenB> createState() => _ScreenBState();
}

class _ScreenBState extends State<ScreenB> {
  @override
  Widget build(BuildContext context) {
    return Material(
      child: Center(child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          const Text('im screen B!'),
          Text('my title is: ${widget.title}'),
          Container(height:20),
          GestureDetector(
            onTap: (){
              context.pop();
            },
            child: const Text(
              'Press Here to Close me out!',
            ),
          ),
        ],
      )),
    );
  }
}



class ScreenC extends StatefulWidget {
  const ScreenC({super.key, required this.title});
  final String title;

  @override
  State<ScreenC> createState() => _ScreenCState();
}

class _ScreenCState extends State<ScreenC> {
  @override
  Widget build(BuildContext context) {
    return Material(
      child: Center(child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          const Text('im screen C!'),
          Text('my title is: ${widget.title}'),
          Container(height:20),
          GestureDetector(
            onTap: (){
              context.pop();
            },
            child: const Text(
              'Press Here to Close me out!',
            ),
          ),
        ],
      )),
    );
  }
}

```

**main_router.dart**
```dart
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';

import 'main.dart';
import 'main_router_scaffold.dart';

final GoRouter router = GoRouter(
  debugLogDiagnostics: true,
  initialLocation:'/',
  navigatorKey: rootNavigatorKey,
  routes: <RouteBase>[



        StatefulShellRoute(
        builder: (context, state, navigationShell) {
            return navigationShell;
        },
        navigatorContainerBuilder: (BuildContext context,
        StatefulNavigationShell navigationShell,
        List<Widget> children) {
            return ScaffoldWithNavBarWithState(navigationShell: navigationShell, children: children);
        },
        branches: <StatefulShellBranch>[

            StatefulShellBranch(
                routes: [
                        GoRoute(
                        path: '/',
                          builder: (BuildContext context, GoRouterState state) {

                            var theTitle = "Hello friends";

                            return MyHomePage(title:theTitle);
                          },
                          routes: <RouteBase>[
                            GoRoute(
                              path: 'screenb.php',
                              name: 'screenB',
                              builder: (BuildContext context, GoRouterState state) {

                                debugPrint('***** I AM BUILDING SCREEN B *****');
                                var theTitle = "Hi this is Screen B";

                                return ScreenB(title: theTitle);
                              },
                            ),



                            GoRoute(
                              path: 'screenc.php',
                              name: 'screenC',
                              builder: (BuildContext context, GoRouterState state) {

                                debugPrint('***** I AM BUILDING SCREEN C *****');
                                var theTitle = "Hi this is Screen C";

                                return ScreenC(title: theTitle);
                              },
                            ),


                          ],
                        ),
              ]
            )

        ],
      )

    ]
);
```

**main_router_scaffold.dart**
```dart
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';


class ScaffoldWithNavBarWithState extends StatefulWidget {
  const ScaffoldWithNavBarWithState({
    Key? key,
    required this.children,
    required this.navigationShell,}) : super(key: key ?? const ValueKey<String>('ScaffoldWithNavBar'));
  /// Body, i.e. the index stack
  //final Widget body;
  final List<Widget> children;

  /// The navigation shell and container for the branch Navigators.
  final StatefulNavigationShell navigationShell;

  @override
  State<ScaffoldWithNavBarWithState> createState() => _ScaffoldWithNavBarWithStateState();
}

class _ScaffoldWithNavBarWithStateState extends State<ScaffoldWithNavBarWithState> {


  @override
  void initState(){
    super.initState();
  }


  @override
  Widget build(BuildContext context) {


    return
      PopScope(

        onPopInvoked: (popped) async {
          //debugPrint('what!');
        },

        child: CupertinoTabScaffold(
          resizeToAvoidBottomInset: true,
          //controller:bottomTabBarController,
          restorationId: 'cupertino_tab_scaffold',
          key: const ValueKey('tab_scaffold'),
          tabBar:

          CupertinoTabBar(
            items: const <BottomNavigationBarItem>[

              BottomNavigationBarItem(icon: Icon(Icons.house), label: 'First Screen'),
              BottomNavigationBarItem(icon: Icon(Icons.house), label: 'Second Screen'),

            ],
            currentIndex: widget.navigationShell.currentIndex,
            onTap: (int tappedIndex) {

              context.pop();

              return widget.navigationShell.goBranch(
                  tappedIndex
                //navigatorKey: _bottomNavBranches[tappedIndex].navigatorKey
              );


            },
          ),
          tabBuilder: (BuildContext context, int index) {

            return widget.children[index];

          },
        ),
      );
  }
}

```

</details>


### Screenshots or Video

<details open>
<summary>Screenshots / Video demonstration</summary>

[Upload media here]

</details>


### Logs

<details open><summary>Logs</summary>

```console
[Paste your logs here]
```

</details>


### Flutter Doctor output

<details open><summary>Doctor output</summary>

```console
Flutter 3.24.2 • channel stable • https://github.com/flutter/flutter.git
Framework • revision 4cf269e36d (3 days ago) • 2024-09-03 14:30:00 -0700
Engine • revision a6bd3f1de1
Tools • Dart 3.5.2 • DevTools 2.37.2

```

</details>