【发布时间】: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.
}
根据我从教程和文章中看到的,这段代码应该可以工作,但我似乎找不到原因。
【问题讨论】: