What is the difference between between context.watch and context.read in flutter_bloc?

I just learn about a cubit in a flutter. I learn in the tutorial video, so in that video, the mentor made a login page that contains an email and password text field and one login button. In that video, the mentor still uses the old version of flutter_bloc. There is a warning when I follow one of the code lines

child: ElevatedButton(
  onPressed: () {
    context.watch<AuthCubit>().signIn(
     _emailController.text,
     _passwordController.text);
}

that code is written inside the onPressed function button. it says that context.bloc is deprecated. When I try to run the app it returns an error because the flutter_bloc's version I used has not supported null safety so I upgrade it to the current version (7.3.1) and I found this in version 6.1.0 changelog (you can see it in flutter_bloc change log )

deprecated: context.bloc in favor of context.read and context.watch

Because I don't know the difference I just change context.bloc to context.watch then I run the app again and it returns another error

Tried to listen to a value exposed with a provider, from outside of the widget tree.

This is likely caused by an event handler (like a button's onPressed) that called
Provider.of without passing `listen: false`.

To fix, write:
Provider.of<AuthCubit>(context, listen: false);

It is unsupported because may pointlessly rebuild the widget associated to the
the event handler, when the widget tree doesn't care about the value.
...

And when I change it to context.read it works. I am wondering about the difference between them

Upvotes: 10

Views: 16187

Answers (1)

Daniel
Daniel

Reputation: 576

context.watch<T>() listens to changes on T

context.read<T>() returns T without listening to it

You were calling

context.watch<AuthCubit>().signIn(
     _emailController.text,
     _passwordController.text);

in the ElevatedButton's onPressed() and thereby listening to AuthCubit exposed with provider, from outside of the widget tree. When you change it to use context.read<AuthCubit> you return AuthCubit without listening to it from outside the widget tree.

Upvotes: 4

Related Questions