Getting error in riverpod statement in flutter

Advertisements

I have started learning flutter with a channel guide,

In the first lesson I am getting an error,

I am getting an error in the following line

final number=watch(provider);

and here is full code

final provider=Provider<int>((ref)=>20);

class HomeScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(title: Text('RiverPod'),),
      body: Center(child: Consumer(
          builder: (context,watch,child){
            final number=watch(provider);
//getting an error in above statement, red line under watch(provider)
            return Text(number.toString());

          },
          child: Text('Riverpod')),),
    );
  }
}

>Solution :

Actually, the builder is defined something like

 builder: (BuildContext context, WidgetRef ref, Widget? child) {

So the second one provide WidgetRef and you can get .watch from this ref.

You can refactor like this to avoid misconception

builder: (context, ref, child) {
  final number = ref.watch(provider);

Leave a ReplyCancel reply