Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

go_router and flutter_bloc: Unhandled Exception: No GoRouter found in context

I have wrapped the MaterialApp with a BlocProvider / BlocListener

I get an error

"Unhandled Exception: 'package:go_router/src/router.dart': Failed assertion: line 280 pos 12: 'inherited != null': No GoRouter found in context" from the Listener callback
Widget build(BuildContext context) {
    return BlocProvider<AuthenticationBloc>(
      create: (context) => AuthenticationBloc()..add(AppStarted()),
      child: BlocListener<AuthenticationBloc, AuthenticationState>(
        listener: (context, state) {
          if (state is AuthenticationUnauthenticated) {
            context.goNamed(LoginPage.routeName);
          }
          if (state is AuthenticationAuthenticated) {
            context.goNamed(NavigationBarContainer.routeName);
          }
        },
        child: MaterialApp.router(
            title: 'Flutter Demo',
            routeInformationProvider: _router.routeInformationProvider,
            routeInformationParser: _router.routeInformationParser,
            routerDelegate: _router.routerDelegate,
            theme: ThemeData(
              primarySwatch: Colors.blue,
            )),
      ),
    );
  }
like image 661
fvisticot Avatar asked Jan 01 '26 00:01

fvisticot


1 Answers

You are attempting to navigate with context from higher up in the widget tree than go_router gets inserted.

I don't know where your GoRouter() routerConfig is, and where it is called from when you use a RouterDelegate, (maybe you don't need to use a delegate?) but you need to call your GoRouter configuration directly, and navigate from that.

So you need to change:

context.goNamed(LoginPage.routeName)

to

routerConfig.goNamed(LoginPage.routeName)

For me, you can see I pass the routerConfig to MaterialApp.router, and I also navigate directly from that, with routerConfig.go(HOME), from above the MaterialApp:

    ref.watch(authStatusServiceProvider).whenData((authStatus) {
      switch (authStatus) {
        case AuthenticationStatusEnum.authenticated:
          routerConfig.go(HOME);
          break;
        case AuthenticationStatusEnum.unauthenticated:
          routerConfig.go(LOGGED_OUT_HOME);
          break;
        default:
          routerConfig.go(LOGGED_OUT_HOME);
          break;
      }
    });

    return MaterialApp.router(
      theme: lightTheme,
      debugShowCheckedModeBanner: false,
      darkTheme: darkTheme,
      routerConfig: routerConfig,
    );
  }

All credit goes to darshankawar on Github.

like image 92
BeniaminoBaggins Avatar answered Jan 04 '26 11:01

BeniaminoBaggins



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!