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

标签 flutter bloc state-management

构建方法内部:

  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 to reduce the amount of boilerplate code needed as well as bloc-specific performance 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/

相关文章:

flutter - 根据参数更改 BlocBuilder 的 bloc

normalization - 如何使用 ngrx/entity(EntityState 和 EntityAdapter)规范化深度嵌套的数据

reactjs - MobX 和 React Native 功能组件 : How can we implement mobX in React Native Functional Component?

flutter - 为什么riverpod甚至无法在项目中初始化?找不到方法 : 'Error.throwWithStackTrace'

flutter - 在有状态小部件外部调用方法以使用 flutter Bloc 更新 UI

json - Flutter:根据类型对 ListView 项目进行排序

bloc 的 flutter bloc 最佳实践

flutter - 将 ChangeNotifier 从 provider 迁移到 hooks_riverpod

flutter - 在 Stack 中将点击事件传递给后面的 child

flutter - 制作具有动态行数的文本