首页 > 解决方案 > 使用不包含“BlocName”的上下文调用 BlocProvider.of()

问题描述

我在使用MultiBlocProvider并通过小部件传递 blocContext 时遇到问题。我在 ShopScreen 中有一个 MultiBlocProvider,在其中有一个过滤器按钮,它显示来自 ModalBottomSheet 的类别列表。像这样:

模态底页

当我从列表中选择不同的类别时,我必须更新商店屏幕。所以,我用过滤器按钮包装了这个 BlocConsumer,我必须将上下文传递给 modalBottomSheet,所以我使用了 BlocProvider.value - 当我按下过滤器按钮时,它会显示这个错误 - 错误

我的多块提供商:

  MultiBlocProvider(
      providers: [
        BlocProvider<ProductsBloc>(create: (_) => productBloc),
        BlocProvider<CategoryBloc>(create: (_) => CategoryBloc()),
        BlocProvider<BannerBloc>(
            create: (_) => BannerBloc()..add(ShowBannerEvent())),
      ],

过滤器按钮

 BlocConsumer<CategoryBloc, CategoryStates>(
                    builder: (context, cateState) {
                      return InkWell(
                        onTap: () {
                          FocusScope.of(context).unfocus();
                          showModalBottomSheet(
                              context: context,
                              builder: (context) => BlocProvider.value(
                                  value:
                                      BlocProvider.of<CategoryBloc>(context)
                                        ..add(ShowCategoryEvent()),
                                  child: CategoryBottomSheet()),
                              isScrollControlled: true);
                        },
                        child: SizedBox(
                          height: 50.h,
                          width: 50.w,
                          child: SvgPicture.asset(
                            'assets/fillter_button.svg', ),),);
                    },
                    listener: (context, cateState) {
                      if (cateState is CategorySelectedState)
                        widget.categoryId = cateState.categoryId;
                    },
                  ),

有什么遗漏吗?

标签: flutterdartbloc

解决方案


如果你想访问一个块,你应该使用context.read<CategoryBloc>().

例如:

context.read<CategoryBloc>().add(ShowCategoryEvent());

推荐阅读