Are you tired of writing ref.read(myProvider)
or ref.watch(myProvider)
all the time in your Riverpod code? There's a neat tip to make your code cleaner and shorter.
The Problem with Repetitive Code
When you use Riverpod, you often need to get a provider's value using ref.read()
or ref.watch()
. Doing this repeatedly for the same provider can make your code look busy, like ref.read(userSessionRepositoryProvider).someMethod()
. This adds extra text that might feel like unnecessary "boilerplate."
The Simple Solution: Use Extensions on Ref
You can create special additions, called extensions, directly on the Ref
object provided by Riverpod. This lets you add your own custom ways to get providers without writing read()
or watch()
every time.
Here's how it might look:
extension UserSessionRepositoryProvider on Ref {
UserSessionRepository get userSessionRepository =>
read(userSessionRepositoryProvider);
UserSessionRepository get userSessionRepository$ =>
watch(userSessionRepositoryProvider);
}
How These Extensions Work
In this example, we create an extension specifically for accessing a UserSessionRepository
. We add getters like userSessionRepository
. This getter simply calls read(userSessionRepositoryProvider)
for you behind the scenes. Now, instead of writing ref.read(userSessionRepositoryProvider)
, you can just write the much shorter ref.userSessionRepository
.
Accessing Streaming Data
The example also shows userSessionRepository$
. The $
at the end is just a common way developers show that this property might give you a stream or something that changes over time, accessed here using watch()
. You could name it differently or just use watch
within a regular getter if that works better for your project style.
Write Cleaner Code
Using these extensions helps you write code that's easier to read and shorter. As shown in the image's other code block, you can now just use ref.userSessionRepository
directly where you need the repository instance, cutting down on boilerplate.