JVE999
JVE999

Reputation: 3517

Flutter: Why is Provider a better option than a class called AppGlobal with only static singletons?

From what I understand about the flutter package, Provider, is that it's a way to share objects between widgets. I know another way of doing this is to create a class, say AppGlobal, and define various static variables that the whole app could use. It's suggested that Provider is a better way of doing that, but I don't understand why that is.

Upvotes: 22

Views: 7278

Answers (2)

Jemolah
Jemolah

Reputation: 2192

An answer to the question should take different aspects into account:

  1. Testability - not much of a difference. Both cases require code change to replace either the singleton itself or the "provided singleton"
  2. Code Coupling - not much of a difference either (see comment on testability)
  3. Scoping - Singletons most often live through the lifecycle of the whole application. It would be error prone to manage a singleton for some widget subtree. Here provider definitely has its strengths by taking care of creation and disposal.
  4. UI updating - when using singletons this must be completely hand coded with setState which will produce lots of error prone boilerplate code. Provider provides this already under the hood.
  5. Listeners - changing state in one part of the application should notify all consumers of that state. With singletons this has to be built by hand. Provider provides this already under the hood.
  6. Lazy Loading - By default, values are lazy-loaded, which means they are called the first time the value is read instead of the first time the provider is created. This can be disabled by lazy: false

Hope this answers the question in more depth.

Upvotes: 18

Rutvik Sanghavi
Rutvik Sanghavi

Reputation: 49

A quick search through the web and it seems like a global instance of a variable is not the best idea since it is not testable, and it makes the code very coupled with the AppGlobal class.

Here is a link that describes what I am talking about and it does a great job with examples.

Global Access vs Scoped Access with Provider

Upvotes: 4

Related Questions