rrousselGit / flutter_hooks

React hooks for Flutter. Hooks are a new kind of object that manages a Widget life-cycles. They are used to increase code sharing between widgets and as a complete replacement for StatefulWidget.
MIT License
3.12k stars 176 forks source link

Provide an example using both Provider and Hooks #87

Closed wstrange closed 4 years ago

wstrange commented 5 years ago

I'm a newbie - and perhaps this is not the right place for this sample, but I am not 100% clear on how hooks and Provider interact with each other, and what is the best practice.

For example, when do I want to use a ChangeNotifierProvider instead of a useListenable hook?

Can hooks pass providers down the tree to child widgets - or is that strictly what Providers is for?

If I pass down a ChangeNotifierProvider to a widget that uses hooks, how do I "wire" that in to the useListenable hook?

(Apologies if these questions don't make any sense!)

stephenwil commented 5 years ago

You can write a custom hook that would implement the same logic as your ChangeNotifierProvider and then simply use that Hook in any child widget is one option.

rrousselGit commented 5 years ago

Hooks typically want to use Provider.value:

final store = useReducer(reducer);

return Provider.value<Store<T>>(
  value: store,
  child: Provider.value<T>(
    value: store.state,
    child: <something>
  ),
);

where you can then do:

Provider.of<Store<T>>(context)
  .dispatch(SomeAction);

and:

Widget build(context) {
  return Text(Provider.of<T>(context).toString());
}
stargazing-dino commented 4 years ago

@rrousselGit In the Provider docs, you show a method to have the StatefulWidget be the object which represents your app's state. Would this be possible with a HookWidget or no since you wouldn't be able to access its state in the build method?

rrousselGit commented 4 years ago

Closing as riverpod.dev contains a fair amount of examples