Repository: flutter
Issue: [go_router]: Bad state: Future already completed on context.pop()
Labels: package,a: error message,has reproducible steps,P2,p: go_router,team-go_router,triaged-go_router,found in release: 3.27,found in release: 3.28

### Steps to reproduce

1. Go to this [dartpad](https://dartpad.dev/?id=2608e901f8ca64058881594d9066284f) and run the code locally. (Go_router version 14.6.2)
2. Click on the Button 
3. Click on the cancel button

### Expected results

Loading animation stops

### Actual results

Loading animation does not stop because there is some kind of race condition. The `CancelScreen` is popped shortly before the loading animation dialog is popped which causes the Error. If I put a wait in between (see my comment in code) it works fine.

Not sure if it is linked to this older issue: https://github.com/flutter/flutter/issues/123369

### Code sample

[Sample dartpad](https://dartpad.dev/?id=2608e901f8ca64058881594d9066284f)
<details open><summary>Code sample ()</summary>

```dart
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:go_router/go_router.dart';

void main() => runApp(const MyApp());

final pageShellNavigatorKey = GlobalKey<NavigatorState>();
final rootNavigatorKey = GlobalKey<NavigatorState>();

@TypedGoRoute<HomeRoute>(
  path: '/',
  routes: [
    TypedGoRoute<CancelScreenRoute>(path: 'cancel'),
  ],
)
@immutable
class HomeRoute extends GoRouteData {
  @override
  NoTransitionPage<void> buildPage(BuildContext context, GoRouterState state) {
    return NoTransitionPage(
      child: MyHomePage(title: 'title'),
    );
  }
}

@immutable
class CancelScreenRoute extends GoRouteData {
  static final GlobalKey<NavigatorState> $parentNavigatorKey =
      pageShellNavigatorKey;

  @override
  NoTransitionPage<void> buildPage(BuildContext context, GoRouterState state) {
    return NoTransitionPage(
      child: CancelScreen(),
    );
  }
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  static CancelScreenRoute cancelScreenFactory(GoRouterState state) =>
      CancelScreenRoute();

  static HomeRoute homeFactory(GoRouterState state) => HomeRoute();

  @override
  Widget build(BuildContext context) {
    return MaterialApp.router(
      routerConfig: GoRouter(
        navigatorKey: rootNavigatorKey,
        routes: [
          ShellRoute(
            navigatorKey: pageShellNavigatorKey,
            builder: (context, GoRouterState state, child) {
              return child;
            },
            routes: [
              GoRouteData.$route(path: '/', factory: homeFactory, routes: [
                GoRouteData.$route(
                  path: 'cancel',
                  parentNavigatorKey: pageShellNavigatorKey,
                  factory: cancelScreenFactory,
                ),
              ]),
            ],
          ),
        ],
      ),
    );
  }
}

class MyHomePage extends StatefulWidget {
  final String title;

  const MyHomePage({
    super.key,
    required this.title,
  });

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  Future<bool> showEditDialog() async {
    final partialJson = await GoRouter.of(context).push(
      '/cancel',
    );

    // waiting here fixes it
    /*await Future.delayed(const Duration(seconds: 1), () {
      print('One second has passed.');
    });*/

    return true;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            ElevatedButton(
                child: Text('button'),
                onPressed: () => wrapEitherWithLoadingAndError(
                      context: context,
                      eitherFunction: showEditDialog,
                      onSuccess: (_, __) {
                        // maybe show success dialog here
                      },
                    )),
          ],
        ),
      ),
    );
  }
}

class CancelScreen extends StatelessWidget {
  const CancelScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ElevatedButton(
        child: Text('cancel'),
        onPressed: GoRouter.of(context).pop,
      ),
    );
  }
}

class LoadingModal {
  static void showLoadingDialog(
    BuildContext context, {
    bool useRootNavigator = true,
  }) async {
    await showDialog<void>(
      context: context,
      barrierDismissible: false,
      useRootNavigator: useRootNavigator,
      builder: (BuildContext context) {
        return const Dialog(
          backgroundColor: Colors.transparent,
          elevation: 0,
          child: Center(
            child: CircularProgressIndicator(
              valueColor: AlwaysStoppedAnimation<Color>(Colors.black),
            ),
          ),
        );
      },
    );
  }
}

Future<void> wrapEitherWithLoadingAndError<T extends dynamic>({
  required BuildContext context,
  required FutureOr<bool> Function() eitherFunction,
  required FutureOr<void> Function(BuildContext, bool) onSuccess,
}) async {
  LoadingModal.showLoadingDialog(
    context,
    useRootNavigator: false,
  );

  final result = await eitherFunction();

  if (context.mounted) {
    if (GoRouter.of(context).canPop()) {
      GoRouter.of(context).pop(result);
    }

    if (result) {
      onSuccess(context, result);
    }

    return;
  }
}

```

</details>

### Logs

<details open><summary>Logs</summary>

```
[ERROR:flutter/runtime/dart_vm_initializer.cc(40)] Unhandled Exception: Bad state: Future already completed
#0      _AsyncCompleter.complete (dart:async/future_impl.dart:84:31)
#1      ImperativeRouteMatch.complete (package:go_router/src/match.dart:456:15)
#2      GoRouterDelegate._completeRouteMatch (package:go_router/src/delegate.dart:171:14)
#3      GoRouterDelegate._handlePopPageWithRouteMatch.<anonymous closure> (package:go_router/src/delegate.dart:151:9)
<asynchronous suspension>
```
</details>


### Flutter Doctor output

<details open><summary>Doctor output</summary>

```console
[✓] Flutter (Channel stable, 3.27.1, on Manjaro Linux 6.1.119-1-MANJARO, locale en_US.UTF-8)
[✓] Android toolchain - develop for Android devices (Android SDK version 33.0.1)
[✓] Chrome - develop for the web
[✓] Linux toolchain - develop for Linux desktop
[✓] Android Studio (version 2024.2)
[✓] Connected device (2 available)
[✓] Network resources
```

</details>