Provider Package

Learn about the provider package, which will be used for state management.

Since the provider is a third-party package, we need to install it first.

Add dependency

To add a provider, run the following command in the terminal inside the project folder. This will add the package in pubspec.yaml.

flutter pub add provider

How it works

The provider provides something to its underlying widget. We know that in Flutter we have widget trees that make up our whole UI, so a provider providing something at one node will be known by all of its child widgets. This is the key fundamental in the provider package. And what does it provide? Its actual state or value.

Let’s see how this works by looking at an example. Remember our counter app that increments the counter and changes its state using the setState() of the stateful widget? In this lesson, we’ll rewrite that program and use the provider package to achieve this feat. Since we no longer need the setState() function, we can use a stateless widget instead of the stateful one.

Implementation

First, we have created a class called CounterProvider that has just one state called counter and extends the ChangeNotifier class. While setting its value via setter, we call notifyListeners() to notify objects for whatever is listening to it.

The ChangeNotifier class comes with Flutter SDK itself, and from here, we get notifyListeners().

We can see this line of code inside our widgets:

CounterProvider counterProvider =
    Provider.of<CounterProvider>(context, listen: true);

This line of code is responsible for listening to the CounterProvider and updating its state whenever the notifyListeners() of this class is called.

Get hands-on with 1200+ tech skills courses.