lazyPutIfAbsent<T> static method
Registers a lazy dependency builder only if it doesn't already exist.
If a dependency with the same type and tag exists (either instantiated or as a lazy builder), this method does nothing. Otherwise, it registers the lazy builder. The dependency instance is created only when find is called for the first time.
This combines the benefits of lazyPut (deferred initialization) and putIfAbsent (conditional registration).
Parameters:
builder: Function that creates the dependency instancetag: Optional identifier for multiple instancesfenix: Iftrue, rebuilds the dependency after deletion
Example:
// First call registers the lazy builder
Dependency.lazyPutIfAbsent<DatabaseService>(
() => DatabaseService(),
);
// Second call does nothing (builder already registered)
Dependency.lazyPutIfAbsent<DatabaseService>(
() => DatabaseService(),
);
// With tag and phoenix mode
Dependency.lazyPutIfAbsent<CacheService>(
() => CacheService(),
tag: 'primary',
fenix: true,
);
// Instance is created only when first accessed
final db = Dependency.find<DatabaseService>();
Implementation
static void lazyPutIfAbsent<T>(
T Function() builder, {
String? tag,
bool fenix = false,
}) {
final key = _getKey(T, tag: tag);
// Check if dependency already exists (either instantiated or lazy)
if (_dependencyStore[key] != null || _lazyBuilders[key] != null) {
return;
}
_lazyBuilders[key] = builder;
if (fenix) {
_fenixKeys.add(key);
}
}