gpt4 book ai didi

flutter - 使用不包含 MainBloc 类型的 Bloc 的上下文调用 BlocProvider.of()

转载 作者:行者123 更新时间:2023-12-02 19:51:27 26 4
gpt4 key购买 nike

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

我试过this所以问题,但它离我正在寻找的东西真的很远,我也尝试按照错误的建议进行操作,但没有成功,这是我收到的消息:

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.
}

从我从教程和文章中看到的内容来看,这段代码应该可以工作,但我似乎找不到为什么不可以。

最佳答案

问题是除非您在 MaterialApp 之上提供 InheritedWidget,否则您无法跨路由访问 InheritedWidget。我建议将您的新路由包装在 BlocProvider.value 中,以将现有的 block 提供给新路由,例如:

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

您可以在 bloc documentation 中找到有关此内容的更多详细信息。

关于flutter - 使用不包含 MainBloc 类型的 Bloc 的上下文调用 BlocProvider.of(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58088109/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com