Can't watch object instance with Riverpod

Issue

In a Flutter web project, I’m having this issue with Riverpod:

Consumer(
  builder: (context, watch, child) {
    final om=watch(human);  
    return Text(om.name); }

‘watch’ is underlined and the compiler says: The expression doesn't evaluate to a function, so it can't be invoked.
The quick fix suggestion is to remove human from the parenthesis. Of course, that’s not happening while I have still have some fight left in me. This is the definition of human:

final human=ChangeNotifierProvider((ref)=>Human()); 

class Human with ChangeNotifier{String name="tananana";}

I couldn’t tell you what version of Riverpod I’m importing, as I’ve had to leave it unspecified in pubspec.yaml so that it may work out its conflicts with the other imports, but I’m on channel master running version 2.9.0-1.0.pre.294

Any advice would be valued.

Solution

You’re most likely using version 1.0.x of Riverpod, which changes the syntax for listening providers.

TL;DR, Consumer doesn’t receive "watch" as parameter but a "ref". So to watch a provider, you need to do:

Consumer(
  builder: (context, ref, child) {
    final om = ref.watch(human);

See the migration guide for more informations

Answered By – Rémi Rousselet

Answer Checked By – Mary Flores (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *