State Management with Flutter Riverpod.

Huzaifa Ahmed
3 min readJan 30, 2021

--

As many of you know that there are many libraries or packages for state management with flutter, as you can see in the picture below.

Riverpod is one of them, it is created by the same person who created Provider package, Remi Rousellete and it is one of the most used package in Flutter and it is also recommended by Flutter itself in its documentation.

But there are some issues with provider that cannot be solved in provider package so Author provided us with new solution called riverpod, some of them issues are following:

  • Why do I have a ProviderNotFoundException?
  • How can I make that my state automatically disposed of when not used anymore?
  • How to make a provider that depends on other (potentially complex) providers?

These issues are listed in riverpod documentation.

Introduction

Riverpod comes with some very cool features that I like the most, some of them are:

  • Declare your providers globally.
  • catches programming errors at compile time rather than at runtime
  • removes nesting for listening/combining objects
  • ensures that the code is testable.
  • Dependency Injection made easy.
  • Extension methods on the context for riverpod methods.

How Riverpod actually work?

First, we will wrap our Material or Root widget App in a ProviderScope.

This will register all our providers without any further configuration.

Next, we will declare our provider classes globally in which we will implement our business logic.

In this provider we can also register our services like navigation or dialog services, so that’s how Dependency Injection (DI) made easy in riverpod.

All your app providers will connect automatically with your app, that’s remarkable right?

But wait, how to use that provider in an app?

There are many ways to consume providers in your app, but one the approach I use most and it is very straight-forward, like below:

final authProviderState = useProvider(authProvider.state);

useProvider is basically a method or a hook that is provided by hooks_riverpod, it takes a provider with its state.

It means you can easily watch your state changes in your app.

To read from the provider you can use an extension method on the context like below:

context.read(authProvider).login()

Conclusion:

Riverpod is actually very easy to use when it comes to complex state management and especially when it used with flutter hooks.

See the tutorial below on Hands-on with Riverpod by making a todo app.

Also, subscribe if you like my content 🙂❤️️🎥

️Follow me on :

Youtube: https://www.youtube.com/c/LivDev
LinkedIn: https://www.linkedin.com/in/huzaifa-ahmed-mohammad/ Instagram: https://www.instagram.com/_huzaifaahmed/
Github: https://github.com/Huzaifaahmed20

--

--

Huzaifa Ahmed
Huzaifa Ahmed

Responses (1)