Home > Net >  Why does ChangeNotifierProvider exist?
Why does ChangeNotifierProvider exist?

Time:10-25

According to Flutter's documentation here (https://flutter.dev/docs/development/data-and-backend/state-mgmt/simple),

one way to control the state management is to use ChangeNotifierProvider(or InheritedWidget) when one of its descendants is a Consumer which is rebuilt when the underlying ChangeNotifier changes. Flutter's team reiterates that approach on the official youtube Flutter channel.

However, that means that some business logic element (ChangeNotifier) is now part of the Widget tree (which otherwise is all about how the UI will look like). So I don't understand why those classes (ChangeNotifierProvider,InheritedWidget,Consumer) even exist.

In particular, why isn't the following approach superior:

-Business logic is a singleton and a ChangeNotifier.

-Instead of Provider(...), for every Widget depending on the business logic simply do this:

BusinessLogicSingleton.instance.addListener(() {

      setState(() {

      });

at initState(...).

What am I missing here?

CodePudding user response:

You can indeed do that, but then you'd also have to remember to close the listener on dispose. Providers handle that automatically.

CodePudding user response:

How do you plan to set state in stateless widgets? Also following your suggested method, you would be rebuilding the entire widget with setstate, vs building only a specific part even for complex widgets if you were to use consumers.

  • Related