-
-
Notifications
You must be signed in to change notification settings - Fork 523
Description
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.
- External state tracking: I could maintain an external
Map<Type, bool>
to track initialization status for eachProvider
type, but this would introduce boilerplate, be prone to errors (e.g., not updating the map correctly), and tightly couple theProvider
usage with this external tracking mechanism, defeating some of the benefits ofprovider
. - Relying on
lazy
: Whilelazy
defaults totrue
(meaningcreate
is called on first access), settinglazy: 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.