MAA
MAA

Reputation: 1355

When to use ChangeNotifier?

In the flutter sample explaining how to use the Provider package, there are two models, Catalog and Model. For the Catalog model, ChangeNotifier is not used, but for the Cart model it's used.

Cart model Catalog model

Why is ChangeNotifier used for the Cart model and not Catalog model?

My thinking is that the Cart model depends on changes outside (in the catalog model). The catalog model is hard-coded and hence no need to notify anyone of changes.

Is my thinking correct?

PS: this is my first app and I'm a complete noob when it comes to state management.

Upvotes: 2

Views: 832

Answers (1)

Dipesh Dulal
Dipesh Dulal

Reputation: 518

Yes you are correct.

The ChangeNotifier as the name suggests stands for notifying the changes. As you can see the function notifyListners() called at catalog and add functions are used to notify the listeners subscribed to the notifier using Consumer widget or using Consumer.of(). So as to when to use ChangeNotifiers ? You can use then whenever there are state changes in a model dependant upon some other view deep in the tree that you cannot get to them directly.

enter image description here

So from this widget tree you can clearly see that MyCatalog and MyCart are totally different from each other in the UI but are dependant logically. i.e. you need to notify the cart widget whenever user changes the MyListItem.

One possible solution for this scenario is that using global variables (sort of) or a variable that is at top of MyCatalog and MyCart in the tree. So that when MyCatalog changes the state the ChangeNotifier at the top of tree would know of the change and notify the MyCart that is listening to the changes.

ChangeNotifiers are used in such scenario where we need to lift the state up as the documentation says here or you could use it when you need the values deep in the tree that you cannot directly give. In case of react we call it props drilling. Giving the state to the child widgets in the tree.

We could acheive this without using providers if I am not wrong. Making MyApp a statefull widget and passing the state to MyCatalog and MyCart widget. so that the renders would know to get the state from. But what if you added another widget that depends on the state deep in the tree. Would you pass the state down ? or Would you use the Provider ? all depends upon you and your application.

Upvotes: 6

Related Questions