replace<P> static method
Replaces an existing dependency with a new instance.
This method preserves the permanence status of the original instance when replacing it with the new one.
Parameters:
child
: The new instance to replace the existing onetag
: Optional tag to identify the specific instance to replace
Throws an exception if the instance is not found.
Implementation
static Future<void> replace<P>(P child, {String? tag}) async {
try {
// Get instance info to determine if it should be permanent
final info = Get.getInstanceInfo<P>(tag: tag);
final permanent = info.isPermanent ?? false;
// Delete existing instance and put the new one
final deleted = await delete<P>(tag: tag, force: permanent);
if (!deleted) {
throw BindError<String>(
controller:
"Failed to delete existing instance before replacement for ${P.toString()}",
tag: tag,
);
}
// Register the new instance with the same permanence status
Get.put(child, tag: tag, permanent: permanent);
} catch (e) {
// Rethrow with more context if it's not already a BindError
if (e is! BindError) {
// Create a new error with the available information
throw BindError<String>(
controller:
"Error replacing instance of type ${P.toString()}: ${e.toString()}",
tag: tag,
);
}
rethrow;
}
}