[英]Flutter BLoC BlocProvider.of() called with a context that does not contain a Bloc of type
[英]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.