go_router 和 flutter_bloc:未处理的异常:在上下文中找不到 GoRouter

fvi*_*cot 10 routes dart flutter flutter-bloc flutter-go-router

我用 BlocProvider / BlocListener 包装了 MaterialApp

我收到一个错误

"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
Run Code Online (Sandbox Code Playgroud)
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,
            )),
      ),
    );
  }
Run Code Online (Sandbox Code Playgroud)

Ben*_*ins 7

context您正在尝试从小部件树中比插入的 go_router 更高的位置进行导航。

我不知道你的 routerConfig 在哪里,以及当你使用, (也许你不需要使用委托?)GoRouter()时从哪里调用它,但你需要直接调用你的配置,并从中导航。RouterDelegateGoRouter

所以你需要改变:

context.goNamed(LoginPage.routeName)
Run Code Online (Sandbox Code Playgroud)

routerConfig.goNamed(LoginPage.routeName)
Run Code Online (Sandbox Code Playgroud)

对我来说,你可以看到我传递了routerConfigto MaterialApp.router,并且我还直接从该位置导航,使用routerConfig.go(HOME), 从上面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,
    );
  }
Run Code Online (Sandbox Code Playgroud)

所有功劳都归功于Github 上的 darshankawar