Introduction
Riverpod is another state management solution by the same person who created provider.
Some of the main feature of riverpods are:
- catch programing errors at compilation rather than at runtime
- removes nesting for listening/combining objects.
- ensures that the code is testable
- Declare your provider globally and use it anywhere you want.
How to get started?
Install riverpod in your app by inserting the following line in your pubspec.yaml
dependencies:
...
flutter_riverpod: ^0.12.1
Then In your main.dart locate the main function where runApp is called, wrap MyApp widget with ProviderScope from flutter_riverpod, like this:
...
import 'package:flutter_riverpod/flutter_riverpod.dart';
void main() {
runApp(
const ProviderScope(child: MyApp()),
);
}
Create a new file called counter_notifier.dart, and insert following code in it.
final counterProvider = StateProvider((ref) => 0);
There are different types of Riverpods named:
- Provider
- StateProvider
- StreamProvider
- FutureProvider
- StateNotifierProvider
In this counter app, we will use StateProvider in which we directly read and mutate the state in our widget.
In your main.dart, in your Home class update code with the following:
class Home extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Counter example')),
body: Center(
child: Consumer(builder: (context, watch, _) {
final count = watch(counterProvider).state;
return Text('$count');
}),
),
floatingActionButton: FloatingActionButton(
onPressed: () => context.read(counterProvider).state++,
child: const Icon(Icons.add),
),
);
}
}
In the above code, we are using Consumer from flutter_riverpod, the main benefit of using the consumer is that it will build only the widget which is changed not the whole app like here we have Text widget which shows our count, it will only build when the counter changes.
The next new thing in riverpod is that we have extension methods on the context for reading a provider directly in our on pressed function by which you can mutate state and update the counter.
Conclusion
As you can see we only have to wrap our app once in ProviderScope and then we can use as many providers as we want by declaring them globally.
If your like this article follow me on Hasnode and other platforms
Thank you ❤️️
Happy Coding 💻