提供者 .read() 与 .watch()

Provider .read() vs .watch()

我刚刚将我的 flutter_bloc 库更新为 6.1.1,其中状态:

bloc' is deprecated and shouldn't be used. Use context.read or context.watch instead. Will be removed in v7.0.0. Try replacing the use of the deprecated member with the replacement.

这是我必须更改的部分代码:

class ContractSubscriptionForm extends StatelessWidget {
  final ContractSubscription contractSubscription;
  const ContractSubscriptionForm(this.contractSubscription, {Key key})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (context) => ContractSubscriptionFormBloc(
        contractSubscription,
        context.read<CoursesGroupBloc>().state.coursesGroupList,  // <---change to .read()
      ),
      child: SubscriptionFormBody(),
    );
  }
}

我所做的更改是:context.bloc<CoursesGroupBloc>().state.coursesGroupList,context.read<CoursesGroupBloc>().state.coursesGroupList,,现在可以正常工作了。

.read() 函数的文档中,我阅读了以下内容:

This method is the opposite of [watch]. It will not make widget rebuild when the value changes and cannot be called inside [StatelessWidget.build]/[State.build]. On the other hand, it can be freely called outside of these methods.

出于某种原因,这没有任何意义,因为上面的代码在 StatelessWidget 的 build 中并且正在使用 .read() 函数而不是 .watch()

我是不是漏掉了什么?

您没有在 StatelessWidget 的构建中调用 context.read,您是在创建 ContractSubscriptionFormBloc 期间在 BlocProvider 中调用的。 如果您尝试执行以下操作:

class example extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    context.read<CoursesGroupBloc>().state.coursesGroupList;
    //the rest of your code
  }
}

会出现这个错误: 尝试在 build 方法或提供程序

update 回调中使用 context.read<bloc>