useContext can only be called from the build method of HookWidget

2.8k Views Asked by At

I am creating a simple single value program in Riverpod. There is a floating action button which on click increments the counter value.

Here's the MyHomePage widget:

final provider = StateNotifierProvider((ref) => CounterNotifier());

class MyHomePage extends HookWidget {
  @override
  Widget build(BuildContext context) {
    final counterModel = useProvider(provider.state);
    return Scaffold(
      appBar: AppBar(
        title: Text('Counter'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text('You have pushed the button this many times'),
            Text('${counterModel.count}',
                style: Theme.of(context).textTheme.headline4),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          context.read(provider).increment();
        },
        child: Icon(Icons.add),
      ),
    );
  }
}

and then running it as a Windows app.

enter image description here

2

There are 2 best solutions below

1
On

For my case i was assigning the useProvider() method outside the build method of a HookWidget.

0
On

When changing

class YourName extends StatelessWidget

to

class YourName extends HookWidget

you almost certainly need to stop your application and restart it typing

flutter run

in your console.