gpt4 book ai didi

flutter - 为什么我们不能在具有 bloc 属性的 Consumer 内部使用 BlocProvider.of(blocContext) ?什么是解决方案?

转载 作者:行者123 更新时间:2023-12-05 05:47:06 27 4
gpt4 key购买 nike

构建方法内部:

  return BlocBuilder<UserCubit, UserState>(
bloc: UserCubit("firstName", "lastName"),
builder: (BuildContext blocContext, UserState state) {
print(BlocProvider.of<UserCubit>(blocContext).user.fullName); // error here
});

错误:

BlocProvider.of() called with a context that does not contain a UserCubit.

显然不是这样的......

问题是,如果 BlocBuilder/BlocConsumerbloc 属性不为 null,我该如何访问 cubit。

最佳答案

基本上这是因为小部件 BlocBuilder 没有在您的 BuildContext blocContext 中注入(inject)提供的 bloc 参数。

flutter_bloc documentationBlocBuilderStreamBuilder 一样工作,它不会在你的小部件树中注入(inject)任何东西它只会“听”你提供的 UserCubitbloc 属性中。因为 UserCubit 没有注入(inject)到您的小部件树中,您将永远无法使用 BlocProvider 访问它。

BlocBuilder handles building a widget in response to new states.BlocBuilder is analogous to StreamBuilder but has simplified API toreduce the amount of boilerplate code needed as well as bloc-specificperformance improvements.

当您使用 BlocBuilder 时,您将需要依赖 state 值来访问您的 bloc 或 cubit 中的属性,并且您必须注入(inject)您的 bloc/cubit通过使用父 BlocProvider 在小部件树中,这是一个示例:

class MyWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
final userCubit = UserCubit("firstName", "lastName");

// Using BlocProvider to inject your UserCubit
return BlocProvider(
create: (_) => userCubit,
child: BlocBuilder<UserCubit, UserState>(
// Still using the instance of userCubit as the injected instance is not
// available in the widget tree at this point.
bloc: userCubit,
builder: (blocContext, state) {
// Now that you are in your builder with an up-to-date blocContext you can
// have access to your instance of UserCubit with BlocProvider.
print(BlocProvider.of<UserCubit>(blocContext).user.fullName);
return Text("State is $state");
},
),
);
}
}

You can try the full example on DartPad

关于flutter - 为什么我们不能在具有 bloc 属性的 Consumer 内部使用 BlocProvider.of(blocContext) ?什么是解决方案?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71071187/

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