I'm starting to use riverpod and I'm trying to migrate my existing code which was using provider.
With provider, the Providers were scoped in the widget tree. Only the children of the Provider widget could access its model.
It says in the riverpod's doc:
Allows easily accessing that state in multiple locations. Providers are a complete replacement for patterns like Singletons, Service Locators, Dependency Injection or InheritedWidgets.
* "Providers" here refers to the
Providerclass of the packageriverpod.
And the provider package was a simplification/wrapper/API around InheritedWidgets so I guess what was possible with provider is also possible with riverpod.
But I cannot manage to find out how to do it.
Here is a small example of what I am trying to migrate.
class Counter extends ValueNotifier<int> {
Counter(): super(0);
}
class MyWidget extends StatelessWidget {
const MyWidget();
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider<Counter>(
create: (_) => Counter();
child: Builder(
builder: (context) {
return Row(
children: [
IconButton(
onPressed: () {
context.read<Counter>().value++;
},
icon: Icon(Icons.add),
),
Text('Count: ${context.watch<Counter>().value}'),
],
);
},
),
);
}
}
Wherever there is a MyWidget widget, the sub-widget has access to a unique/scoped model Counter.