Skip to content

[go_router] Unable to use GoRouter.of(context).namedLocation() inside redirect. #116855

@2shrestha22

Description

@2shrestha22

Steps to Reproduce

  1. Use GoRouter.of(context).namedLocation() inside redirect.

This cause error:

  String? authGuard(BuildContext context, GoRouterState state) {
    // If not logged in redirects to login page also providing
    // next page to redirect after login
    if (authBloc.isLoggedIn) {
      return null;
    } else {
      return GoRouter.of(context).namedLocation(
        Routes.login,
        queryParams: {'redirect_to': state.location},
      );
    }
  }

This works fine but GoRouterState.namedLocation is deprecated:

String? authGuard(BuildContext context, GoRouterState state) {
    // If not logged in redirects to login page also providing
    // next page to redirect after login
    if (authBloc.isLoggedIn) {
      return null;
    } else {
      return state.namedLocation(
        Routes.login,
        queryParams: {'redirect_to': state.location},
      );
    }
  }

Expected results:
Should not throw any exception.

Actual results:
Throws _AssertionError ('package:go_router/src/router.dart': Failed assertion: line 300 pos 12: 'inherited != null': No GoRouter found in context)

Code sample
GoRouter _getRouter(AuthBloc authBloc) {
  /// Returs login path if not logged in else returns null;
  String? authGuard(BuildContext context, GoRouterState state) {
    // If not logged in redirects to login page also providing
    // next page to redirect after login
    if (authBloc.isLoggedIn) {
      return null;
    } else {
      return GoRouter.of(context).namedLocation(
        Routes.login,
        queryParams: {'redirect_to': state.location},
      );
    }
  }

  return GoRouter(
    debugLogDiagnostics: true,
    refreshListenable: GoRouterRefreshStream(authBloc.stream),
    routes: <GoRoute>[
      GoRoute(
        path: '/',
        name: Routes.home,
        builder: (_, __) => const HomePage(),
        routes: [
          GoRoute(
            path: 'login',
            name: Routes.login,
            builder: (_, __) => const LoginPage(),
            redirect: (BuildContext context, GoRouterState state) {
              /// Redirects to next page after login
              if (authBloc.isLoggedIn) {
                if (state.queryParams['redirect_to']?.isNotEmpty ?? false) {
                  return state.queryParams['redirect_to']!;
                } else {
                  return '/';
                }
              } else {
                return null;
              }
            },
          ),
          GoRoute(
            path: 'profile',
            name: Routes.profile,
            builder: (_, __) => const ProfilePage(),
            redirect: authGuard,
          ),
          GoRoute(
            path: 'myLayouts',
            name: Routes.myLayouts,
            builder: (_, __) => const UserLayoutsPage(),
            redirect: authGuard,
          ),
          GoRoute(
            name: Routes.faq,
            path: 'faq',
            builder: (_, __) => const FaqPage(),
          ),
          GoRoute(
            name: Routes.about,
            path: 'about',
            builder: (_, __) => const AboutPage(),
          ),
        ],
      ),

      // Push Routes
      // Below this there are push routes which means that routes should be
      // used imperatively (context.push()) instead of declaratively (context.go())
      GoRoute(
        path: '/layoutDetail',
        name: Routes.layoutDetail,
        builder: (_, state) => LayoutDetailPage(layout: state.extra as Layout),
      ),
      GoRoute(
        name: Routes.fullscreenImage,
        path: '/fullscreenImage',
        builder: (_, GoRouterState state) =>
            FullScreenImage(imageUrl: state.queryParams['imageUrl']!),
      ),
      GoRoute(
        name: Routes.layoutForm,
        path: '/layoutForm',
        builder: (_, state) => LayoutFormPage(layout: state.extra as Layout?),
      ),
    ],
  );
}
Logs
                    ══╡ EXCEPTION CAUGHT BY FOUNDATION LIBRARY ╞════════════════════════════════════════════════════════
                    The following assertion was thrown while dispatching notifications for GoRouteInformationProvider:
                    No GoRouter found in context
                    'package:go_router/src/router.dart':
                    Failed assertion: line 300 pos 12: 'inherited != null'
                    
                    When the exception was thrown, this was the stack:
                    #2      GoRouter.of (package:go_router/src/router.dart:300:12)
                    #3      _getRouter.authGuard (package:cocbase/app/app.dart:92:23)
                    #4      _getRouteLevelRedirect (package:go_router/src/redirection.dart:136:42)
                    #5      _getRouteLevelRedirect.processRouteRedirect (package:go_router/src/redirection.dart:131:7)
                    #6      _getRouteLevelRedirect (package:go_router/src/redirection.dart:154:12)
                    #7      redirect.processRedirect.processTopLevelRedirect (package:go_router/src/redirection.dart:81:11)
                    #8      redirect.processRedirect (package:go_router/src/redirection.dart:108:14)
                    #9      SynchronousFuture.then (package:flutter/src/foundation/synchronous_future.dart:41:35)
                    #10     redirect (package:go_router/src/redirection.dart:116:30)
                    #11     GoRouteInformationParser.parseRouteInformationWithDependencies (package:go_router/src/parser.dart:78:65)
                    #12     _RouterState._processRouteInformation (package:flutter/src/widgets/router.dart:707:8)
                    #13     _RouterState._handleRouteInformationProviderNotification (package:flutter/src/widgets/router.dart:726:5)
                    #14     ChangeNotifier.notifyListeners (package:flutter/src/foundation/change_notifier.dart:351:24)
                    #15     GoRouteInformationProvider.value= (package:go_router/src/information_provider.dart:54:7)
                    #16     GoRouter.go (package:go_router/src/router.dart:187:31)
                    #17     GoRouter.goNamed (package:go_router/src/router.dart:200:7)
                    #18     GoRouterHelper.goNamed (package:go_router/src/misc/extensions.dart:32:25)
                    #19     AppDrawer.build.<anonymous closure> (package:cocbase/core/widgets/app_drawer.dart:79:42)
                    #20     _InkResponseState.handleTap (package:flutter/src/material/ink_well.dart:1072:21)
                    #21     GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:253:24)
                    #22     TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:627:11)
                    #23     BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:306:5)
                    #24     BaseTapGestureRecognizer.acceptGesture (package:flutter/src/gestures/tap.dart:276:7)
                    #25     GestureArenaManager.sweep (package:flutter/src/gestures/arena.dart:163:27)
                    #26     GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:464:20)
                    #27     GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:440:22)
                    #28     RendererBinding.dispatchEvent (package:flutter/src/rendering/binding.dart:337:11)
                    #29     GestureBinding._handlePointerEventImmediately (package:flutter/src/gestures/binding.dart:395:7)
                    #30     GestureBinding.handlePointerEvent (package:flutter/src/gestures/binding.dart:357:5)
                    #31     GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:314:7)
                    #32     GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:295:7)
                    #36     _invoke1 (dart:ui/hooks.dart:169:10)
                    #37     PlatformDispatcher._dispatchPointerDataPacket (dart:ui/platform_dispatcher.dart:341:7)
                    #38     _dispatchPointerDataPacket (dart:ui/hooks.dart:94:31)
                    (elided 5 frames from class _AssertionError and dart:async)
                    
                    The GoRouteInformationProvider sending notification was:
                      Instance of 'GoRouteInformationProvider'
                    ════════════════════════════════════════════════════════════════════════════════════════════════════
❯ flutter analyze     
Analyzing clashly...                                                    
No issues found! (ran in 2.9s)
❯ flutter doctor -v                  
[✓] Flutter (Channel stable, 3.3.9, on Arch Linux 6.0.12-arch1-1, locale en_US.UTF-8)
    • Flutter version 3.3.9 on channel stable at /home/sangam/fvm/versions/3.3.9
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision b8f7f1f986 (3 weeks ago), 2022-11-23 06:43:51 +0900
    • Engine revision 8f2221fbef
    • Dart version 2.18.5
    • DevTools version 2.15.0

[!] Android toolchain - develop for Android devices (Android SDK version 33.0.0)
    • Android SDK at /home/sangam/Android/Sdk
    • Platform android-33, build-tools 33.0.0
    • ANDROID_HOME = /home/sangam/Android/Sdk
    • Java binary at: /opt/android-studio/jre/bin/java
    • Java version OpenJDK Runtime Environment (build 11.0.13+0-b1751.21-8125866)
    ! Some Android licenses not accepted.  To resolve this, run: flutter doctor --android-licenses

[✓] Chrome - develop for the web
    • CHROME_EXECUTABLE = /usr/bin/google-chrome-stable

[✓] Linux toolchain - develop for Linux desktop
    • clang version 14.0.6
    • cmake version 3.25.1
    • ninja version 1.11.1
    • pkg-config version 1.8.0

[✓] Android Studio (version 2021.3)
    • Android Studio at /opt/android-studio
    • 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 11.0.13+0-b1751.21-8125866)

[✓] Connected device (3 available)
    • POCO F1 (mobile) • c7ca2666 • android-arm64  • Android 12 (API 32)
    • Linux (desktop)  • linux    • linux-x64      • Arch Linux 6.0.12-arch1-1
    • Chrome (web)     • chrome   • web-javascript • Google Chrome 108.0.5359.98

[✓] HTTP Host Availability
    • All required HTTP hosts are available

! Doctor found issues in 1 category.

Metadata

Metadata

Assignees

No one assigned

    Labels

    P2Important issues not at the top of the work listfound in release: 3.3Found to occur in 3.3found in release: 3.7Found to occur in 3.7has reproducible stepsThe issue has been confirmed reproducible and is ready to work onp: go_routerThe go_router packagepackageflutter/packages repository. See also p: labels.workaround availableThere is a workaround available to overcome the issue

    Type

    No type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions