Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Provider vs ValueNotifier Flutter

Tags:

Can someone explain the difference between using Provider package and using ValueNofifier?

Right now I’m using ValueNotifier and ValueListenableBuilder in my app and I see so much similarity between this and using Providers and Consumers. Both have listeners which rebuild widgets with the latest data provided and both use ChangeNotifier and notifyListeners.

So what is the difference and when should we choose one of them instead of the other?

Thanks

like image 334
Morez Avatar asked Sep 12 '20 10:09

Morez


1 Answers

As far as my experience is concerned on using both the things in the app, the major difference is that

Provider can provide changes in any part of the app, like any where with the use of notifyListener(), and can be accessed using anywhere in the app. However, there is a possibility of bug in using a global ValueNotifier, which is not recommended. Technically, doesn't gives you much control on bug tracking when the code becomes big.

Provider(
  create: (_) => MyModel(),
  child: ...
)

Other major difference:

Provider gives you the power to make use of Multiple Providers and can be stored in a single Provider array only, however, in ValueNotifier, you are ver much restricted to use one value at a time. For using multiple ValueNotifiers, you have to create multiple ValueNotifiers, and then dispose it all every time.

MultiProvider(
  providers: [
    Provider<Something>(create: (_) => Something()),
    Provider<SomethingElse>(create: (_) => SomethingElse()),
    Provider<AnotherThing>(create: (_) => AnotherThing()),
  ],
  child: someWidget,
)

It is basically neat way of keeping your business logic separated with your normal app logic.

like image 121
Alok Avatar answered Sep 21 '22 13:09

Alok