[英]BlocProvider.of() called with a context that does not contain a Bloc of type MainBloc
I have a MainBloc that resides inside a main route, this route has a bottom app bar with multiple sub-routes, I want the same BLoC to run on all five sub-routes so that when one of them changes the state of the block the others will see the effect.我有一个位于主路由内的 MainBloc,该路由有一个带有多个子路由的底部应用程序栏,我希望在所有五个子路由上运行相同的 BLoC,以便当其中一个更改块的 state其他人会看到效果。
I tried this SO question but its really far from what I'm looking for, also I tried following what the error advised me to, but didn't work, here is the message that I got:我尝试了这个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()).
Main route:主要路线:
@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
);
one of the sub-routes:子路线之一:
@override
Widget build(BuildContext context) {
final MainBloc bloc = BlocProvider.of<MainBloc>(context);
return /...; //here I have the context of this sub-route.
}
from what I've seen from tutorials and articles this code should work, but I can't seem to find why not.从我从教程和文章中看到的,这段代码应该可以工作,但我似乎找不到原因。
As this child has the bottom app bar: child: /..., //here I have the bottom app bar
then I assume that the MultiBlocProvider(..)
is not wrapping the whole part of app which is using this Bloc, my suggestion here is to wrap the "MaterialApp" with "MultiBlocProvider".因为这个孩子有底部的应用栏: 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
//..
)
The problem is you cannot access InheritedWidgets across routes unless you provide the InheritedWidget above MaterialApp.问题是您无法跨路由访问 InheritedWidget,除非您在 MaterialApp 上方提供 InheritedWidget。 I would recommend wrapping your new route in BlocProvider.value to provide the existing bloc to the new route like:我建议将您的新路线包装在 BlocProvider.value 中,以将现有集团提供给新路线,例如:
Navigator.of(context).push(
MaterialPageRoute<MyPage>(
builder: (_) {
return BlocProvider.value(
value: BlocProvider.of<MyBloc>(context),
child: MyPage(),
);
},
),
);
You can find more detailed information about this in thebloc documentation您可以在bloc 文档中找到有关此的更多详细信息
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.