Dependency Injection
Consider the following class that defines the basic structure for a login using the repository pattern:
Now, we define a class that implements our repository:
Next, we need to use our AuthRepository
in a way that makes our code maintainable and testable. In this case, we can use the Provider
class to create an instance of AuthRepository
.
We define our repository as a global variable:
With this, we can now use our repository in our views or notifiers.
For example, let's imagine we have a LoginNotifier
class that extends StateNotifier
and needs our AuthRepository
to perform the login action:
Now, if we want to write the respective test, we'll notice that we need to mock the behavior of the Dio class. For this, we simply use the overrideCreator
function:
note
Unlike the StateNotifierProvider
and StateNotifierArgumentsProvider
classes, the auto-dispose
feature is not available for the Provider
class and its variants such as ArgumentsProvider
, FactoryProvider
, and FactoryArgumentsProvider
. You must manually release the resources of these classes using the dispose
function.
For example, if we update the definition of our authRepository
to execute code for resource cleanup, this would be the result:
#
Working with argumentsIf you need to provide some values before the provider creates your data, you can use the ArgumentsProvider
class.
Now you can pass an instance of Dio as an argument using setArguments.
For example
#
FactoryProviderIf every time we retrieve the data from a provider, we need that data to always be a new instance
, we should use the FactoryProvider
class.
Now, to retrieve the data of type AuthRepository
from our global variable authRepository
, we must use the get
function.
note
One instance of FactoryProvider
does not have a dispose
function because every time we call get, we receive a new instance. In this case, the get
function returns an instance of FactoryElement
, and this class contains the dispose
function.
Example:
#
Factory with argumentsThe FactoryArgumentsProvider
works similarly to FactoryProvider
but also allows us to pass arguments to be retrieved inside the creator callback.
#
TIPInstead of defining our repositories as global variables, we can define them as static data, achieving the same result but with much more readable code.