What is Riverpod?
Riverpod is a reactive caching and data-binding framework for Flutter
It can automatically fetch, cache, combine, and re-compute data
It can effectively handle errors
How to use Riverpod?
Install required packages
dependencies:
# the core Riverpod package
flutter_riverpod:
# the annotation package containing @riverpod
riverpod_annotation:
dev_dependencies:
# dart tool to run code generators
build_runner:
# the Riverpod code generator
riverpod_generator:
# riverpod_lint makes it easier to work with Riverpod
riverpod_lint:
# import custom_lint too as riverpod_lint depends on it
custom_lint:
Create Providers
Use the Riverpod generator to create providers. All we need to do is define the provider using one of the following syntaxes and let the Riverpod generator worry about what type of provider to create.
@riverpod
String label(LabelRef ref) {
return 'Hello world';
}
@riverpod
class Counter extends _$Counter {
@override
int build() {
return 0;
}
void increament() {
state++;
}
void decreament() {
state--;
}
}
Create Consumers
Wrap MyApp() with ProviderScope()
Use Consumer / ConsumerWidget / ConsumerStatefulWidget
Pass WidgetRef ref to Widget build()
Use ref.read() ⟶ to read a provider’s state just once. Useful for calling methods inside Notifier.
Use ref.watch() ⟶ to watch a provider’s state and rebuild UI when the state changes. Returns only new value.
Use ref.listen() ⟶ to listen to a provider’s state and invoke a callback when the state changes. Returns old and new values.