You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter使用MultiBlocProvider时BlocProvider.of()找不到对应Bloc问题求助

问题根源

你代码的核心问题是showModalBottomSheet的builder回调参数context和外层BlocConsumer提供的可用context重名,发生了变量遮蔽:
你在builder内部调用BlocProvider.of<CategoryBloc>(context)时,使用的是ModalBottomSheet新生成的上下文,这个上下文还没有注入上层的CategoryBloc实例,因此触发找不到Bloc的报错。

解决方案

只需要修改builder的参数名,避免遮蔽外层可用的context即可,修改后的筛选按钮代码如下:

BlocConsumer<CategoryBloc, CategoryStates>(
  builder: (context, cateState) {
    return InkWell(
      onTap: () {
        FocusScope.of(context).unfocus();
        showModalBottomSheet(
          context: context,
          // 把builder的参数重命名为modalContext,避免遮蔽外层context
          builder: (modalContext) => BlocProvider.value(
            // 这里使用外层BlocConsumer的context获取Bloc实例
            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;
    }
  },
)

可选优化

你也可以提前在onTap回调里先拿到Bloc实例,不需要依赖上下文,完全避免重名问题:

onTap: () {
  final categoryBloc = BlocProvider.of<CategoryBloc>(context);
  FocusScope.of(context).unfocus();
  showModalBottomSheet(
    context: context,
    builder: (context) => BlocProvider.value(
      value: categoryBloc..add(ShowCategoryEvent()),
      child: CategoryBottomSheet(),
    ),
    isScrollControlled: true
  );
},

内容的提问来源于stack exchange,提问作者Abrar Lasebai

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 13:15:04