Provider .read() Vs .watch()

- 1 answer

I just updated my flutter_bloc library to 6.1.1 in which states:

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

Here is a part of code that I did have to change:

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

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

The part I did change is this: context.bloc<CoursesGroupBloc>().state.coursesGroupList, to<CoursesGroupBloc>().state.coursesGroupList, and is now working.

In the documentation for the .read() function I read the following:

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

For some reason, this makes no sense, since the upper code is within a build of a StatelessWidget and is working with the .read() function but not with the .watch().

Am I missing something?



you didn't call inside the StatelessWidget's build, you did that inside BlocProvider during creating ContractSubscriptionFormBloc. if you try to do the following:

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

this error will appear: Tried to use<bloc> inside either a build method or the update callback of a provider