flutter_bloc 找不到正确的提供商

flutter_bloc could not find the correct provider

我有一个 Cubit 从 API 获取数据。我想将它连接到 UI,所以我首先在该小部件的顶部添加了一个 BlocProvider。这给了我一个错误,所以我用 BlocProvider 包裹了 MaterialApp ,它给出了同样的错误。之后,我尝试将它放在我想要访问它的路线上,结果相同。

MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: getThemeData(),
      onGenerateRoute: _router.generateRoutes,
      initialRoute: _store.get('users', defaultValue: {}).isEmpty
          ? '/onboarding'
          : '/dashboard',
);

routes.dart

final PANCubit _panCubit = PANCubit(PANRepository());
  Route<dynamic> generateRoutes(RouteSettings settings) {
    switch (settings.name) {
      // case '/':
      //   return MaterialPageRoute(builder: (context) => Home());
      case '/':
      case '/onboarding':
        return MaterialPageRoute(
          builder: (context) => BlocProvider.value(
            value: _panCubit,
            child: OnBoarding(),
          ),
        );
...

我想在 UI 中访问它:

OnBoardingView(
  imagePath: process_svg,
  titleWidget: BlocBuilder(
    builder: (context, state) {
      context.read<PANCubit>().getPANInformation(_panText.text);

      if (state is PANLoading) {
        return CircularProgressIndicator();
      } else if (state is PANFetched) {
        return Text(
          'Hey ${state.panInformation.fullName}!',
          style: Theme.of(context).textTheme.headline1,
        );
      } else {
        return Text('Hmmm..Something went wrong.');
      }
    },
  ),
...

您需要在 BlocBuilder 中明确要访问哪个集团:

titleWidget: BlocBuilder<PANCubit, PANState>( // Replace PANState by the type of state
    builder: (context, state) {
      state.getPANInformation(_panText.text);

      if (state is PANLoading) {
        return CircularProgressIndicator();
      } else if (state is PANFetched) {
        return Text(
          'Hey ${state.panInformation.fullName}!',
          style: Theme.of(context).textTheme.headline1,
        );
      } else {
        return Text('Hmmm..Something went wrong.');
      }
    },
  ),