簡體   English   中英

使用不包含 MainBloc 類型的 Bloc 的上下文調用 BlocProvider.of()

[英]BlocProvider.of() called with a context that does not contain a Bloc of type MainBloc

我有一個位於主路由內的 MainBloc,該路由有一個帶有多個子路由的底部應用程序欄,我希望在所有五個子路由上運行相同的 BLoC,以便當其中一個更改塊的 state其他人會看到效果。

我嘗試了這個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.
}

從我從教程和文章中看到的,這段代碼應該可以工作,但我似乎找不到原因。

因為這個孩子有底部的應用欄: 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
  //..
)

問題是您無法跨路由訪問 InheritedWidget,除非您在 MaterialApp 上方提供 InheritedWidget。 我建議將您的新路線包裝在 BlocProvider.value 中,以將現有集團提供給新路線,例如:

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

您可以在bloc 文檔中找到有關此的更多詳細信息

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM