In the last episode, we implemented a simple provider that enabled us to fetch our model data, and while we could change the state of the model, our user interface stayed the same. We need to let Flutter know our model changes, and for that, we must extend the change notifier.
The change notifier acquires listeners and when a change occurs, the model will notify all the various listeners. In order for our state to be rebuilt, we need to use a change provider. We use the change provider much like our previous provider. We simply pass in our model data and we are off to the races. Let’s do this now.
To get started, open your project in progress or download the starter project for this episode.
When we last left off, we created a simple provider object and then passed our model object into the widget tree. Let’s update our model object to extend the notifier.
Open pillar.dart. Update the class definition to extend change notifier.
class Pillar extends ChangeNotifier {
Next, we’ll update all the listeners once the model changes.
In increaseArticleCount, add the following method call:
notifyListeners();
Now, open main.dart.
We’re going to change the Provider to a change notifier provider. Update it to the following:
body: ChangeNotifierProvider<Pillar>(
Believe it or not - that’s all it takes! Build and run. Now tap the Flutter button. This time the article count increases. What is happening is that the model is being increased and when that happens, the model calls notify listeners. Provider just happens to be a listener which then fires off the user interface rebuild. Not bad when compared to stateful widgets!