8

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

Raju Ahmed
  • 1,282
  • 5
  • 15
  • 24

1 Answers1

2

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.

Daniel
  • 546
  • 6
  • 17
  • Thanks man for the answer, but i still have some questions. What is meant by 'outside widget tree'? is it the widget outside BlocProvider or what? – Alun Paranggi Wicaksono Nov 02 '21 at 09:58
  • @AlunParanggi This issue from the provider package discusses what 'outside widget tree' means and why you should avoid listening outside your widget tree – Daniel Nov 02 '21 at 13:42