Skip to content

[go_router]: Bad state: Future already completed on context.pop() #160696

Description

@nietsmmar

Steps to reproduce

  1. Go to this dartpad 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: #123369

Code sample

Sample dartpad

Code sample ()
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;
  }
}

Logs

Logs
[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>

Flutter Doctor output

Doctor output
[✓] 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

Activity

  1. maheshj01 commented on Dec 24, 2024

    @maheshj01
    Member

    Reproducible on stable and the master channel.

    logs
    Restarted application in 61ms.
    Restarted application in 231ms.
    DartError: Bad state: Future already completed
    dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/errors.dart 288:3  throw_
    dart-sdk/lib/async/future_impl.dart 84:31                                    complete
    packages/go_router/src/match.dart 456:5                                      complete
    packages/go_router/src/delegate.dart 171:13                                  [_completeRouteMatch]
    packages/go_router/src/delegate.dart 151:9                                   <fn>
    dart-sdk/lib/_internal/js_dev_runtime/patch/async_patch.dart 610:19          <fn>
    dart-sdk/lib/_internal/js_dev_runtime/patch/async_patch.dart 634:23          <fn>
    dart-sdk/lib/_internal/js_dev_runtime/patch/async_patch.dart 581:31          <fn>
    dart-sdk/lib/async/zone.dart 1676:54                                         runUnary
    dart-sdk/lib/async/future_impl.dart 204:18                                   handleValue
    dart-sdk/lib/async/future_impl.dart 902:44                                   handleValueCallback
    dart-sdk/lib/async/future_impl.dart 931:13                                   _propagateToListeners
    dart-sdk/lib/async/future_impl.dart 513:9                                    callback
    dart-sdk/lib/async/schedule_microtask.dart 40:11                             _microtaskLoop
    dart-sdk/lib/async/schedule_microtask.dart 49:5                              _startMicrotaskLoop
    dart-sdk/lib/_internal/js_dev_runtime/patch/async_patch.dart 186:7           <fn>
    Application finished.
    
    Exited.
    flutter doctor -v
    [✓] Flutter (Channel stable, 3.27.1, on macOS 15.1.1 24B2091 darwin-arm64, locale en-US)
        • Flutter version 3.27.1 on channel stable at /Users/mahesh/Development/flutter
        • Upstream repository https://github.com/flutter/flutter.git
        • Framework revision 17025dd882 (7 days ago), 2024-12-17 03:23:09 +0900
        • Engine revision cb4b5fff73
        • Dart version 3.6.0
        • DevTools version 2.40.2
    
    [✓] Android toolchain - develop for Android devices (Android SDK version 34.0.0)
        • Android SDK at /Users/mahesh/Library/Android/sdk
        • Platform android-35, build-tools 34.0.0
        • ANDROID_HOME = /Users/mahesh/Library/Android/sdk
        • Java binary at: /Applications/Android Studio.app/Contents/jbr/Contents/Home/bin/java
        • Java version OpenJDK Runtime Environment (build 17.0.11+0-17.0.11b1207.24-11852314)
        • All Android licenses accepted.
    
    [✓] Xcode - develop for iOS and macOS (Xcode 16.0)
        • Xcode at /Applications/Xcode.app/Contents/Developer
        • Build 16A242d
        • CocoaPods version 1.16.2
    
    [✓] Chrome - develop for the web
        • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome
    
    [✓] Android Studio (version 2024.1)
        • 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.11+0-17.0.11b1207.24-11852314)
    
    [✓] IntelliJ IDEA Community Edition (version 2021.2.1)
        • IntelliJ at /Applications/IntelliJ IDEA CE.app
        • Flutter plugin version 61.2.4
        • Dart plugin version 212.5080.8
    
    [✓] VS Code (version 1.94.0)
        • VS Code at /Applications/Visual Studio Code.app/Contents
        • Flutter extension version 3.100.0
    
    [✓] Connected device (3 available)
        • macOS (desktop)                 • macos                 • darwin-arm64   • macOS 15.1.1 24B2091 darwin-arm64
        • Mac Designed for iPad (desktop) • mac-designed-for-ipad • darwin         • macOS 15.1.1 24B2091 darwin-arm64
        • Chrome (web)                    • chrome                • web-javascript • Google Chrome 128.0.6613.85
    
    [✓] Network resources
        • All expected network resources are available.
    
    • No issues found!
    
    [!] Flutter (Channel master, 3.28.0-1.0.pre.123, on macOS 15.1.1 24B2091 darwin-arm64, locale en-US)
        • Flutter version 3.28.0-1.0.pre.123 on channel master at /Users/mahesh/Development/flutter_master
        ! Warning: `flutter` on your path resolves to /Users/mahesh/Development/flutter/bin/flutter, which is not inside your current Flutter SDK checkout at
          /Users/mahesh/Development/flutter_master. Consider adding /Users/mahesh/Development/flutter_master/bin to the front of your path.
        ! Warning: `dart` on your path resolves to /Users/mahesh/Development/flutter/bin/dart, which is not inside your current Flutter SDK checkout at
          /Users/mahesh/Development/flutter_master. Consider adding /Users/mahesh/Development/flutter_master/bin to the front of your path.
        ! Unknown upstream repository.
          Reinstall Flutter by following instructions at https://flutter.dev/setup.
        • Framework revision a547c7f050 (10 days ago), 2024-12-13 22:11:39 -0500
        • Engine revision 4e4a430bcd
        • Dart version 3.7.0 (build 3.7.0-243.0.dev)
        • DevTools version 2.41.0
        • If those were intentional, you can disregard the above warnings; however it is recommended to use "git" directly to perform update checks and upgrades.
    
    [✓] Android toolchain - develop for Android devices (Android SDK version 34.0.0)
        • Android SDK at /Users/mahesh/Library/Android/sdk
        • Platform android-35, build-tools 34.0.0
        • ANDROID_HOME = /Users/mahesh/Library/Android/sdk
        • 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 17.0.11+0-17.0.11b1207.24-11852314)
        • All Android licenses accepted.
    
    [✓] Xcode - develop for iOS and macOS (Xcode 16.0)
        • Xcode at /Applications/Xcode.app/Contents/Developer
        • Build 16A242d
        • CocoaPods version 1.16.2
    
    [✓] Chrome - develop for the web
        • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome
    
    [✓] Android Studio (version 2024.1)
        • 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.11+0-17.0.11b1207.24-11852314)
    
    [✓] IntelliJ IDEA Community Edition (version 2021.2.1)
        • IntelliJ at /Applications/IntelliJ IDEA CE.app
        • Flutter plugin version 61.2.4
        • Dart plugin version 212.5080.8
    
    [✓] VS Code (version 1.94.0)
        • VS Code at /Applications/Visual Studio Code.app/Contents
        • Flutter extension version 3.100.0
    
    [✓] Connected device (3 available)
        • macOS (desktop)                 • macos                 • darwin-arm64   • macOS 15.1.1 24B2091 darwin-arm64
        • Mac Designed for iPad (desktop) • mac-designed-for-ipad • darwin         • macOS 15.1.1 24B2091 darwin-arm64
        • Chrome (web)                    • chrome                • web-javascript • Google Chrome 128.0.6613.85
    
    [✓] Network resources
        • All expected network resources are available.
    
    ! Doctor found issues in 1 category.
    
  2. added
    packageflutter/packages repository. See also p: labels.
    has reproducible stepsThe issue has been confirmed reproducible and is ready to work on
    a: error messageError messages from the Flutter framework
    and removed
    in triagePresently being triaged by the triage team
    on Dec 24, 2024
  3. leredirect commented on Jul 1, 2025

    @leredirect

    any workarounds for now? in my case context.pop(true) throws "Bad state: Future already completed" on second call.

  4. nietsmmar commented on Jul 1, 2025

    @nietsmmar
    Author

    @leredirect I am just simply waiting for some time before doing the next call... I don't know of any other workaround yet.

  5. techouse commented on Sep 16, 2025

    @techouse
    Contributor

    @leredirect I am just simply waiting for some time before doing the next call... I don't know of any other workaround yet.

    Same. Using something like

    await Future.delayed(const Duration(milliseconds: 10));

    works, but it's a hack 🙈

  6. koji-1009 commented on Oct 21, 2025

    @koji-1009
    Contributor

    When I tested the following sample, GoRoute worked fine, but GoRouteData.$route did not.

    import 'package:flutter/material.dart';
    import 'package:go_router/go_router.dart';
    
    void main() => runApp(const GoRouterApp());
    // void main() => runApp(const GoRouterBuilderApp());
    
    final pageShellNavigatorKey = GlobalKey<NavigatorState>();
    final rootNavigatorKey = GlobalKey<NavigatorState>();
    
    class GoRouterApp extends StatelessWidget {
      const GoRouterApp({super.key});
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp.router(
          routerConfig: GoRouter(
            navigatorKey: rootNavigatorKey,
            routes: [
              ShellRoute(
                navigatorKey: pageShellNavigatorKey,
                builder: (context, state, child) => child,
                routes: [
                  GoRoute(
                    path: '/',
                    parentNavigatorKey: pageShellNavigatorKey,
                    builder: (context, state) {
                      return const MyHomePage();
                    },
                    routes: [
                      GoRoute(
                        path: 'detail',
                        parentNavigatorKey: rootNavigatorKey,
                        builder: (context, state) {
                          return const DetailScreen();
                        },
                        routes: [
                          GoRoute(
                            path: 'sub',
                            parentNavigatorKey: rootNavigatorKey,
                            builder: (context, state) {
                              return const SubDetailScreen();
                            },
                          ),
                        ],
                      ),
                    ],
                  ),
                ],
              ),
            ],
          ),
        );
      }
    }
    
    class HomeRoute extends GoRouteData {
      const HomeRoute();
      @override
      Widget build(BuildContext context, GoRouterState state) {
        return const MyHomePage();
      }
    }
    
    class DetailRoute extends GoRouteData {
      const DetailRoute();
      @override
      Widget build(BuildContext context, GoRouterState state) {
        return const DetailScreen();
      }
    }
    
    class SubDetailRoute extends GoRouteData {
      const SubDetailRoute();
      @override
      Widget build(BuildContext context, GoRouterState state) {
        return const SubDetailScreen();
      }
    }
    
    class GoRouterBuilderApp extends StatelessWidget {
      const GoRouterBuilderApp({super.key});
    
      static HomeRoute homeFactory(GoRouterState state) => const HomeRoute();
      static DetailRoute detailFactory(GoRouterState state) => const DetailRoute();
      static SubDetailRoute subDetailFactory(GoRouterState state) =>
          const SubDetailRoute();
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp.router(
          routerConfig: GoRouter(
            navigatorKey: rootNavigatorKey,
            routes: [
              ShellRoute(
                navigatorKey: pageShellNavigatorKey,
                builder: (context, state, child) => child,
                routes: [
                  GoRouteData.$route(
                    path: '/',
                    factory: homeFactory,
                    parentNavigatorKey: pageShellNavigatorKey,
                    routes: [
                      GoRouteData.$route(
                        path: 'detail',
                        factory: detailFactory,
                        parentNavigatorKey: rootNavigatorKey,
                        routes: [
                          GoRouteData.$route(
                            path: 'sub',
                            parentNavigatorKey: rootNavigatorKey,
                            factory: subDetailFactory,
                          ),
                        ],
                      ),
                    ],
                  ),
                ],
              ),
            ],
          ),
        );
      }
    }
    
    class MyHomePage extends StatelessWidget {
      const MyHomePage({super.key});
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(title: const Text('Home Screen')),
          body: Center(
            child: FilledButton(
              onPressed: () {
                GoRouter.of(context).push('/detail');
              },
              child: const Text('push to detail'),
            ),
          ),
        );
      }
    }
    
    class DetailScreen extends StatelessWidget {
      const DetailScreen({super.key});
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(title: const Text('Detail Screen')),
          body: Center(
            child: FilledButton(
              onPressed: () {
                GoRouter.of(context).push('/detail/sub');
              },
              child: const Text('push to subdetail'),
            ),
          ),
        );
      }
    }
    
    class SubDetailScreen extends StatelessWidget {
      const SubDetailScreen({super.key});
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(title: const Text('Sub Detail Screen')),
          body: Center(
            child: FilledButton(
              style: ButtonStyle(
                backgroundColor: MaterialStateProperty.all(Colors.red),
              ),
              onPressed: () {
                GoRouter.of(context).pop();
                GoRouter.of(context).pop();
              },
              child: const Text('double pop'),
            ),
          ),
        );
      }
    }

    Adding if (completer.isCompleted) return; to the following function seems to temporarily avoid the Bad State issue. However, this likely doesn't directly resolve the problem that occurs with GoRouteData.$route.

    https://github.com/flutter/packages/blob/go_router-v16.2.5/packages/go_router/lib/src/match.dart#L485-L489

  7. a7medev commented on Dec 26, 2025

    @a7medev

    Any updates here? I'm facing this issue on v17.0.1 after switching to typed routes.

  8. nietsmmar commented on Jan 26, 2026

    @nietsmmar
    Author

    I also still have this isssue.

  9. fingerart commented on Feb 24, 2026

    @fingerart
  10. fingerart commented on Feb 28, 2026

    @fingerart

    This issue only occurs with routes automatically generated by go_router_builder because of the call to GoRouteData.$route.

    @darshankawar @chunhtai , the core requirement for calling context.pop() consecutively is to close multiple preceding pages at once. I’m looking forward to seeing popUntil / removeUntil implemented soon.

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: error messageError messages from the Flutter frameworkfound in release: 3.27Found to occur in 3.27found in release: 3.28Found to occur in 3.28has 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