Quick Summary:

This blog explores the Flutter Riverpod APIs and concepts using simple examples. It is one of the many ways to handle Flutter state management. We have covered the Riverpod Flutter tutorial, its usage, and the benefits of using Riverpod over Provider package.

Table of Contents

Introduction

For beginners, let us start with the basic conceptual understanding to Flutter state management, and the role of Flutter Riverpod repository. Basically, Flutter does take care of state management on its own, however, as your application grows and expands, you might need to share your app state with several classes.

There are numerous options that Flutter provides for managing the states of your application. And here, we are going to talk about Riverpod.

What is Riverpod Flutter?

Riverpod is a reactive caching framework for Flutter/Dart. It can automatically fetch, cache, combine and recompute network requests, while also taking care of errors for you. It is a reconstruction of the Provider package; meaning it reduces dependencies.

However, in the Riverpod vs Provider battle, the advatages of Riverpod over Provider are:

๐ŸŸ  You will no longer get โ€˜provider not foundโ€™ exception
๐ŸŸ  You can define global providers
๐ŸŸ  You can significantly simplifying the combination of “providers”, instead of the tedious and error-prone ProxyProvider.

Uses of Riverpod Flutter:

๐ŸŸ  Catch programming errors at compile-time rather than at runtime
๐ŸŸ  Easily fetch, cache, and update data from a remote source
๐ŸŸ  Perform reactive caching and easily update your UI
๐ŸŸ  Depend on asynchronous or computed state
๐ŸŸ  Write testable code and keeping logic outside the widget tree
๐ŸŸ  Create, use, and combine providers with minimal boilerplate code
๐ŸŸ  Dispose the state of a provider when it is no longer used

Do you wish to optimize your Flutter app performance by filtering widget rebuilds or caching expensive state computations?
Hire Flutter developer from us and they will effortlessly handle your appโ€™s state and enhance its performance.

Installation of Flutter Riverpod

The primary step is to add the latest โ€˜flutter_riverpodโ€™ to โ€˜pubspec.yamlโ€™ file as a dependency.

Copy Text
dependencies:
  flutter:
    sdk: flutter  
  flutter_riverpod: ^2.0.2

ProviderScope

Once Riverpod is installed, we can wrap our root widget with a `ProviderScope`:

Copy Text
void main() {
  // wrap the entire app with a ProviderScope so that widgets
  // will be able to read providers
  runApp(ProviderScope(
    child: MyApp(),
  ));
}
ProviderScope

`ProviderScope` is a widget that stores the state of all the providers we create

๐ŸŸ  They completely replace design patterns such as singletons, service locators, dependency injection, and InheritedWidgets.
๐ŸŸ  They allow you to store some state and easily access it in multiple locations.
๐ŸŸ  They allow you to optimize performance by filtering widget rebuilds or caching expensive state computations.
๐ŸŸ  They make your code more testable, since each provider can be overridden to behave differently during a test.

Creating and Reading a Provider

Here is a simple โ€œHello Worldโ€ screen created using the Provider.

Copy Text
// provider that returns a string value
final helloWorldProvider = Provider((ref) {
  return 'Hello world';
});

This is made of three things:

1. The declaration: `final helloWorldProvider` is the global variable that we will use to read the state of the provider
2. The provider: `Provider< String >` tells us what kind of provider we’re using (more on this below), and the type of the state it holds.
3. A function that creates the state. This gives us a `ref` parameter that we can use to read other providers, perform some custom dispose logic, and more.

To use this provider inside a widget, you will need a reference object. There are 3 ways to achieve that:

1. Using a ConsumerWidget

The simplest way is to use a `ConsumerWidget`:

Copy Text
final helloWorldProvider = Provider((_) => 'Hello world');

// 1. widget class now extends [ConsumerWidget]
class HelloWorldWidget extends ConsumerWidget {
  @override
  // 2. build method has an extra [WidgetRef] argument
  Widget build(BuildContext context, WidgetRef ref) {
    // 3. use ref.watch() to get the value of the provider
    final helloWorld = ref.watch(helloWorldProvider);
    return Text(helloWorld);
  }
}

2. Using a Consumer

As an alternative, we can wrap our `Text` widget with a `Consumer`:

Copy Text
final helloWorldProvider = Provider((_) => 'Hello world');

class HelloWorldWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // 1. Add a Consumer
    return Consumer(
      // 2. specify the builder and obtain a WidgetRef
      builder: (_, WidgetRef ref, __) {
        // 3. use ref.watch() to get the value of the provider
        final helloWorld = ref.watch(helloWorldProvider);
        return Text(helloWorld);
      },
    );
  }
}

3. Using ConsumerStatefulWidget & ConsumerState

Copy Text
final helloWorldProvider = Provider((_) => 'Hello world');

// 1. extend [ConsumerStatefulWidget]
class HelloWorldWidget extends ConsumerStatefulWidget {
  @override
  ConsumerState createState() => _HelloWorldWidgetState();
}

// 2. extend [ConsumerState]
class _HelloWorldWidgetState extends ConsumerState {
  @override
  void initState() {
    super.initState();
    // 3. if needed, we can read the provider inside initState
    final helloWorld = ref.read(helloWorldProvider);
    print(helloWorld); // "Hello world"
  }

  @override
  Widget build(BuildContext context) {
    // 4. use ref.watch() to get the value of the provider
    final helloWorld = ref.watch(helloWorldProvider);
    return Text(helloWorld);
  }
}
Hello World Example

Conclusion

Riverpod is a sane solution to resolve Flutter state management problems, and is surely a better method as compared to Provider. It overcomes the drawbacks of Provider and it turns out to enable a strong architecture for your Flutter application. Get in touch with the best Flutter app development company to leverage this state management solution.

Frequently Asked Questions (FAQs)

Here are the different types of Providers,
๐ŸŸ  Provider
๐ŸŸ  StateProvider
๐ŸŸ  StateNotifierProvider
๐ŸŸ  FutureProvider
๐ŸŸ  StreamProvider
๐ŸŸ  ChangeNotifierProvider (legacy)
๐ŸŸ  NotifierProvider
๐ŸŸ  AsyncNotifierProvider

The only hurdle in using Riverpod Flutter is that there is no documentation available, so developers may find some hustle to disentangle.

Yes, Flutter Riverpod provides good state management and dependency injection in Flutter.

Why Flutter Riverpod?

๐ŸŸ  High performance
๐ŸŸ  Easily update your UI
๐ŸŸ  Catch programming errors at compile-time
๐ŸŸ  Easily fetch, cache, and update data from a remote source

Do you still need more clarity on its usage and development possibilities?

Discover More Possibilities

Build Your Agile Team

Hire Skilled Developer From Us

[email protected]

Your Success Is Guaranteed !

We accelerate the release of digital product and guaranteed their success

We Use Slack, Jira & GitHub for Accurate Deployment and Effective Communication.

How Can We Help You?