Search code examples
flutterprovider

Flutter Provider vs global variables


what is the reason for using Provider (in a simple app) on top of global variables defined in the main file? calling Provider has to be embedded in Build methods, so can be a direct access to global varialbes prvided the main is imported

are the widgets calling Provider somehow automatically marked for rebuild if variables are changed?

until now I am using both Provider and direct access to learn the differences


Solution

  • A global in Dart is not "observable". You can locate the variable, and obtain its current value, but there's no place to register to be informed of changes. This is particularly important if you are including the data as part of a view, or as part of data that is further observed.

    The various state management solutions (including Provider, and my preferred system, Riverpod) are all mechanisms to implement "observable data", which provides three key features: locatability, current value, and registration of ongoing notifications.

    Riverpod in addition has the ability to "override" the locatability, which comes in handy for testing or dependency injection.