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

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


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

  1. Testability - not much of a difference. Both cases require codechange to replace either the singleton itself or the "providedsingleton"
  2. Code Coupling - not much of a difference either (see comment ontestability)
  3. Scoping - Singletons most often live through the lifecycle of the wholeapplication. It would be error prone to manage a singleton for somewidget subtree. Here provider definitely has its strengths by taking care ofcreation and disposal.
  4. UI updating - when using singletons this must be completely hand coded withsetState 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 shouldnotify 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.


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