Search code examples
flutter

What is the benefit of using Provider package over ChangeNotifier plus ListenableBuilder?


We have built-in ChangeNotifier and ListenableBuilder widget and they work together just fine.

What is the benefit of using the Provider package over them? What problem does it solve?


Solution

  • Based on your purposes.

    Short answer: The provider itself is a wrapper around InheritedWidget to make it easier to use and more reusable. ONE of its possibilities is to expand the basic capabilities of the ChangeNotifier, allow to use it in more flexible and maintainable way.


    Detailed answer:

    Using ChangeNotifier + ListenableBuilder is quite limited.

    ChangeNotifier is an implementation of Observer pattern in Flutter's foundation, so its goal to notify other obects about its changes, if they listen to it.

    In case you want to use your ChangeNotifier's instance in few places to share same state, you have to put (provide) THAT instance inside EVERY place, where you use ListenableBuilder. Potential places for error and unexpected behavior.

    That's the moment where provider enters the game. Instead of trying to place this ChangeNotifier instance deeply into a tree of widgets in different places, you provide an instance of a ChangeNotifier to its descendants (down the widget tree) using ChangeNotifierProvider. From now you can access your ChangeNotifier instance everywhere under ChangeNotifierProvider using Consumer class instead of ListenableBuilder.

    An example of using provider you can also find in Flutter official docs.