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

why can't we use BlocProvider.of(blocContext) inside of Consumer with bloc attribute? and what is the solution?

构建方法内部:

  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/BlocConsumer bloc 属性不为空,我如何访问肘部。

基本上是因为小部件 BlocBuilder 没有在您的 BuildContext blocContext.

中注入提供的 bloc 参数

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

访问它

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

当您使用 BlocBuilder 时,您将需要依赖 state 值来访问您的 bloc 或 cubit 的属性,并且您必须将 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