The Get.replace Method
Learn to replace originally injected dependencies with Get.replace.
The challenge of re-injecting dependencies in GetX
GetX is fundamentally designed so we cannot inject a dependency twice with Get.put
. The code below does not work the way we expect it to be:
Press + to interact
// Inject Controller for the first time.Get.put<Controller>(Controller(name: 'Aachman'));// Inject Controller again.Get.put<Controller>(Controller(name: 'Garg'));// Find the injected dependency.print(Get.find<Controller>().name); // prints 'Aachman'
We’d expect that the output is 'Garg'
. However, as GetX finds the dependency that was originally injected, the output is 'Aachman'
.
Solving the issue with Get.replace
For scenarios like this, we have the Get.replace
method. It’s a simple method that replaces the original dependency and injects a new one. Here’s what the same code would look like:
Press + to interact
// Inject Controller for the first time.Get.put<Controller>(Controller(name: 'Aachman'));// Replace Controller instance.Get.replace<Controller>(Controller(name: 'Garg'));// Find the injected dependency.print(Get.find<Controller>().name); // prints 'Garg'
Leveraging Get.replace
with inherited classes
Internally, Get.replace
deletes the previous dependency and injects the new one. This becomes tremendously helpful when we wish to use inherited ...