10

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

Morez
  • 2,085
  • 2
  • 10
  • 33

1 Answers1

8

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.

Alok
  • 8,452
  • 13
  • 55
  • 93
  • I agree with the second part of the answer but for the first part, you can use a global ValueNotfier and use it anywhere in the app. Why is it not recommended and why provider gives you a better way to do the same thing? – Morez Sep 12 '20 at 10:49
  • 1
    It gives you more control over the change @Morez. Like if you make global value and want to change any where, it might be possible that you don't know where you have made changes in the value when the code goes big, but when you have providers, you actually know, since you have set of class methods which handles the change in which you use `notifyListeners()`. Kind of tracking bug more efficiently. **It is generally not a good practice in flutter to make use of `globals`**. You can read more about it, hence first part. – Alok Sep 12 '20 at 10:56