Skip to content

Provide a way to check Provider initialization status #911

@maRci002

Description

@maRci002

Is your feature request related to a problem? Please describe.
I need to conditionally interact with a Provider instance based on whether it has already been initialized. The Provider.of<T>(context) (or context.read<T>()) method, when called, will trigger the create method of the Provider if it hasn't been initialized yet.

This behavior is problematic when I want to perform an action (e.g., refresh data, update state) only if the Provider is already active and its create method has been called. If it hasn't been initialized, I want to avoid triggering its initialization, as that might lead to unnecessary resource allocation. For instance, in a UI component, I might want to refresh data only if the corresponding data Provider is already "alive" and being used by other parts of the widget tree, rather than initializing it.

Describe the solution you'd like
I would like to propose the addition of a static method to the Provider class (or similar, accessible via BuildContext) that allows developers to check whether a Provider of a specific type T has already been initialized within the given BuildContext.

The proposed signature would be:

static bool isInitialized<T>(BuildContext context);

This method would return true if Provider.of<T>(context) has been called at least once for the given type T within the current context's ancestry or lazy == false, and false otherwise. It should not trigger the create method of the Provider if it hasn't been initialized.

This would enable patterns like:

if (Provider.isInitialized<MyDataNotifier>(context)) {
  // Only refresh data if MyDataNotifier is already initialized
  context.read<MyDataNotifier>().refreshData();
} else {
  // MyDataNotifier is not initialized, do nothing or handle differently
}

Describe alternatives you've considered
Currently, there isn't a direct way to achieve this without potentially triggering the create method.

  1. External state tracking: I could maintain an external Map<Type, bool> to track initialization status for each Provider type, but this would introduce boilerplate, be prone to errors (e.g., not updating the map correctly), and tightly couple the Provider usage with this external tracking mechanism, defeating some of the benefits of provider.
  2. Relying on lazy: While lazy defaults to true (meaning create is called on first access), setting lazy: false would force initial creation, but then initalization also happens.

Additional context
It would allow for more precise control over when a Provider's create method is invoked, preventing unnecessary work and improving application responsiveness.

Metadata

Metadata

Assignees

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions