Search code examples
flutterproviderflutter-provider

Is it a best practise to pass provider as an argument to widgets?


Is it a best practise to pass provider as an argument to widgets?

I am aware that we can directly access provider from within the widget. But saw a couple of code snippets passing provider as an argument to child widget. Does it optimize the code? Or any possible leaks?


Solution

  • It is better to access the provider from within the widget that requires it, since the Provider uses the BuildContext (as in Provider.of(context)) to fetch an instance of the requested provided service, based on the location of the widget in the widget tree as it traverses the hierarchy above to find it. You can do it for convenience, but widgets should be encapsulated enough and decoupled enough so as not to depend on higher above widgets to get data fed to them, making them self-sufficient and independent. My two cents.