【问题标题】:BlocProvider.of() called with a context that does not contain a Bloc of type MainBloc使用不包含 MainBloc 类型的 Bloc 的上下文调用 BlocProvider.of()
【发布时间】:2020-01-25 00:56:04
【问题描述】:

我有一个位于主路由内的 MainBloc,该路由有一个底部应用栏,其中包含多个子路由,我希望相同的 BLoC 在所有五个子路由上运行,以便当其中一个更改状态时其他人会看到效果。

我尝试了this SO 问题,但它与我正在寻找的内容相去甚远,我也尝试按照错误建议的方式进行操作,但没有奏效,这是我得到的消息:

This can happen if:
    1. The context you used comes from a widget above the BlocProvider.
    2. You used MultiBlocProvider and didn't explicity provide the BlocProvider types.

    Good: BlocProvider<MainBloc>(builder: (context) => MainBloc())
    Bad: BlocProvider(builder: (context) => MainBloc()).

主要路线:

@override
  Widget build(BuildContext context) {
    return MultiBlocProvider(
      providers: [
        BlocProvider<MainBloc>(
          builder: (BuildContext context) => MainBloc(),
        ),
        BlocProvider<OtherBloc>(
          builder: (BuildContext context) => OtherBloc(),
        ),
      ],
      child: /..., //here I have the bottom app bar with 5 buttons to navigate between sub-routes
);

子路线之一:

@override
  Widget build(BuildContext context) {
    final MainBloc bloc = BlocProvider.of<MainBloc>(context);
    return /...; //here I have the context of this sub-route.
}

根据我从教程和文章中看到的,这段代码应该可以工作,但我似乎找不到原因。

【问题讨论】:

    标签: flutter bloc


    【解决方案1】:

    因为这个孩子有底部应用栏: child: /..., //here I have the bottom app bar 然后我假设MultiBlocProvider(..) 没有包装使用此 Bloc 的应用程序的整个部分,我的建议是用“MultiBlocProvider”包装“MaterialApp”。

    return MultiBlocProvider(
       providers: [..],
       child: MaterialApp(..) // Set MaterialApp as the child of the MultiBlocProvider
      //..
    )
    

    【讨论】:

      【解决方案2】:

      问题是你不能跨路由访问 InheritedWidgets,除非你在 MaterialApp 上面提供 InheritedWidget。我建议将您的新路由包装在 BlocProvider.value 中,以将现有块提供给新路由,例如:

              Navigator.of(context).push(
                MaterialPageRoute<MyPage>(
                  builder: (_) {
                    return BlocProvider.value(
                      value: BlocProvider.of<MyBloc>(context),
                      child: MyPage(),
                    );
                  },
                ),
              );
      

      您可以在bloc documentation找到更多详细信息

      【讨论】:

        猜你喜欢
        • 2021-02-08
        • 2020-10-25
        • 2020-05-20
        • 2020-08-21
        • 2020-12-26
        • 2020-10-16
        • 2020-11-15
        • 2021-06-10
        • 2019-09-29
        相关资源
        最近更新 更多